php是单继承语言,但是如果想在一个class中实现多继承的话,可以使用traits代替.
关于使用.使用关键字trait: 从某个方面,可以理解为class,但是不能实例化
trait中可以定义public,protected,private方法/属性,且父类中如果使用trait,子类也会继承trait,甚至private方法/属性也能继承
trait Hello{
public function sayH(){
echo 'hello ';
}
protected function sayW(){
echo 'world';
}
private function pri(){
echo 'this is a private function';
}
static public function wowo(){
echo 'this is a static function';
}
public function tst(){
echo 'this is trait';
}
}
class one{
use Hello;
public function say(){
$this->pri();
}
public function tst(){
echo 'this is one';
}
}
class two extends one{
public function tst(){
echo 'this is two';
}
}
//偷懒,报错的方法也假设可以执行下去
Hello::wowo(); //this is a static function
$human = new one();
$human->sayH(); //hello
$human->sayW(); //此处报错,调用保护方法
$human->pri(); //此处报错,调用私有方法
$human->tst(); //this is one
one::wowo(); //this is a static function
$human->say(); //可以内部调用 this is a private function
$people = new two();
$people->sayH(); //hello
$people->sayW(); //报错,调用保护方法
$people->pri(); //此处报错,调用私有方法 !注意,私有属性继承下来了
two::wowo(); //this is a static function
$people->say(); //内部调用 this is a private function
$people->tst(); //this is two
?>
可以发现,trait 中的 私有属性 也可以继续下来,可以理解为,two把use Hello 也继承下来了,而且如果子类中有同名方法,则会覆盖父类和trait中的方法
trait中还可以使用抽象类
trait Hello{
abstract public function say();
}
class one{
use Hello;
public function say(){
}
}
?>
当class one中不存在say方法时,便会报错.
当有多个trait时,使用,隔开,或者使用复合traits
trait Hello{
}
trait World{
}
trait HW{
use Hello,World;
}
class one{
use Hello,World;
}
class two{
use HW;
}
?>
以上one 跟 two的实现效果是一样的;
当两个trait钟的方法名一样时,需要用关键字insteadof指定使用哪个,不然就会报错,如果两个都想保留,则可以用as通过别名来实现,同时as也可以实现对方法权限的更改
trait H{
public function A(){
echo 'HA';
}
public function B(){
echo 'HB';
}
}
trait W{
public function A(){
echo 'WA';
}
public function B(){
echo 'WB';
}
}
trait Z{
public function A(){
echo 'ZA';
}
}
//若没有use后{}里的说明,则会报错
//Trait method A has not been applied, because there are collisions with other trait methods on HW
trait HW{
use H,W{
H::A insteadof W,Z;
W::B insteadof H; //W中的B方法取代H中的B方法
Z::A as C;
A as protected;
}
}
class one{
use HW;
public function say(){
$this->A();
}
}
$a = new one();
$a->say(); //HA
$a->A(); //因为被改变了权限,所以无法在外部调用
echo '
';
$a->B(); //WB
echo '
';
$a->C(); //ZA
?>
参考: http://blog.csdn.net/longlongmylove/article/details/7521379