作者共发了2篇帖子。 内容转换:不转换▼
 
点击 回复
324 1
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();

回复帖子

内容:
用户名: 您目前是匿名发表
验证码:
(快捷键:Ctrl+Enter)
 

本帖信息

点击数:324 回复数:1
评论数: ?
作者:巨大八爪鱼
最后回复:巨大八爪鱼
最后回复时间:2016-7-6 23:00
 
©2010-2024 Arslanbar Ver2.0
除非另有声明,本站采用知识共享署名-相同方式共享 3.0 Unported许可协议进行许可。