<?php
/**
* Created by PhpStorm.
* User:
* Date: 2018/12/6
* Time: 14:47
*/
/**
* trait实现了代码的复用
* 并且突破了单继承的限制
* trait不是类,不能实例化
*/
/**
* trait实现了代码的复用优先级问题
* 1.当父类中的方法与trait类,父类中的方法重名了
* 2.本类中方法优先级最高,trait的优先级大于父类的同名方法优先级
* 3.trait类中有多个同名的方法,怎么办
*/
trait Demo1
{
public function hello()
{
return __METHOD__;
}
}
trait Demo2
{
public function hello()
{
return __METHOD__;
}
}
class Test{
public function hello()
{
return __METHOD__;
}
}
class Demo extends Test
{
//等价于把hello1,hello2方法复制进来
use Demo1,Demo2{
//trait类中有多个同名的方法,怎么办
Demo1::hello insteadof Demo2;
Demo2::hello as Demo2Hello;
}
/*public function hello()
{
return __METHOD__;
}*/
public function test1()
{
return $this->hello();
}
public function test2()
{
return $this->Demo2Hello();
}
}
$obj = new Demo();
echo $obj->test1();
echo $obj->test2();
PHP的trait实现了代码的复用并且突破了单继承的限制
猜你喜欢
转载自blog.csdn.net/qq_38866543/article/details/84855592
今日推荐
周排行