php traits 使用,php中traits的使用

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值