PHP Trait
从php5.4开始,为了解决单继承的问题,除了通过implments来实现多接口外,官方提供了一个trait来解决该问题。
<?php
//示例
trait Dog{
public $name = "dog";
public function run(){
echo "This is $this->name run\r\n";
}
public function eat(){
echo "This is $this->name eat\r\n";
}
}
class Animal{
public function run(){
echo "This is animal run\r\n";
}
}
class Cat extends Animal{
use Dog;
public function run(){
echo "This is cat run\r\n";
}
}
$cat = new Cat();
$cat->run();
$cat->eat();
?>
从以上看出,对象调用的优先级为 本类(子类) > trait > 基类(父类)。
本作品采用《CC 协议》,转载必须注明作者和本文链接
Trait 能 new ??