設置 | 登錄 | 註冊

目前共有2篇帖子。

PHP5.4中的trait語句可以支持類的多重繼承

1樓 巨大八爪鱼 2016-7-6 22:59
<?php
trait student {
    public $name;
    public function say() {
        printf('I\'m %s. ', $this->name);
    }
    
    public function eat() {
        printf('<br>%s', __TRAIT__);
    }
}

trait person {
    public $age;
    public $birthday;
    
    public function eat() {
        echo '<br>I don\'t like eating.';
    }
}

trait animal {
    public function eat() {
        echo '<br>What?';
    }
}

class super {
    use student, person, animal {
        student::say as private _say;
        student::eat insteadof person, animal;
    }
    public function say() {
        $this->_say();
        printf('<br>I\'m %d years old. ', $this->age);
    }
}

$s = new super();
$s->name = 'Tom';
$s->age = 15;
$s->say();
$s->eat();
2樓 巨大八爪鱼 2016-7-6 23:00
但是,trait不能用來直接創建對象。
例如不能:
$a = new animal();

內容轉換:

回覆帖子
內容:
用戶名: 您目前是匿名發表。
驗證碼:
看不清?換一張
©2010-2025 Purasbar Ver3.0 [手機版] [桌面版]
除非另有聲明,本站採用知識共享署名-相同方式共享 3.0 Unported許可協議進行許可。