设置 | 登录 | 注册

作者共发了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许可协议进行许可。