分析一下PHP中的Trait机制原理与用法-php教程

资源魔 28 0
本篇文章给各人剖析一下PHP中的Trait机制原理与用法。有肯定的参考代价,有需求的冤家能够参考一下,心愿对各人有所协助。

Trait引见:

一、自PHP5.4起,PHP完成了一种代码复用的办法,称为trait。

二、Trait是为相似PHP的单承继言语二预备的一种代码复用机制。

三、Trait为了缩小单承继言语的限度,使开发职员可以自在地正在没有同条理构造内自力的类中复用method。

四、trait完成了代码的复用,打破了单承继的限度;

五、trait是类,然而不克不及实例化。

六、当类中办法重名时,优先级,以后类>trait>父类;

七、当多个trait类的办法重名时,需求指定拜访哪个,给其它的办法起别号。

示例:

trait Demo1{
 public function hello1(){
  return __METHOD__;
 }
}
trait Demo2{
 public function hello2(){
  return __METHOD__;
 }
}
class Demo{
 use Demo1,Demo2;//承继Demo1以及Demo2
 public function hello(){
  return __METHOD__;
 }
 public function test1(){
  //挪用Demo1的办法
  return $this->hello1();
 }
 public function test2(){
  //挪用Demo2的办法
  return $this->hello2();
 }
}
$cls = new Demo();
echo $cls->hello();
echo "<br>";
echo $cls->test1();
echo "<br>";
echo $cls->test2();

运转后果:

Demo::hello
Demo1::hello1
Demo2::hello2

多个trait办法重名:

trait Demo1{
 public function test(){
  return __METHOD__;
 }
}
trait Demo2{
 public function test(){
  return __METHOD__;
 }
}
class Demo{
 use Demo1,Demo2{
  //Demo1的hello交换Demo2的hello办法
  Demo1::test insteadof Demo2;
  //Demo2的hello起别号
  Demo2::test as Demo2test;
 }
 public function test1(){
  //挪用Demo1的办法
  return $this->test();
 }
 public function test2(){
  //挪用Demo2的办法
  return $this->Demo2test();
 }
}
$cls = new Demo();
echo $cls->test1();
echo "<br>";
echo $cls->test2();

运转后果:

Demo1::test
Demo2::test

更多相干常识,请存眷 PHP中文网!!

以上就是剖析一下PHP中的Trait机制原理与用法的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学 Trait

抱歉,评论功能暂时关闭!