thinkphp5.1学习过程四——trait

為{幸葍}努か 提交于 2019-12-04 23:36:01

<?php
/**
*trait实现了代码的复用
*并且突破了单继承的限制
*trait是类不是类,不能实例化
*/
trait Demo1
{
  public function hello1()
  {
    return __METHOD__;
  }
}
trait Demo2
{
  public function hello2()
  {
    return __METHOD__;
  }
}

class Demo
{
  use Demo1,Demo2;
  public function hello()
  {
    return __METHOD__;
  }
  public function test1()
  {
    return $this->hell1();
  }
  public function test2()
  {
    return $this->hell2();
  }
}
$obj=new Demo();
echo $obj->hello();
echo "<hr>";
echo $obj->hello1();
echo "<hr>";
echo $obj->hello2();
 

trait类的引用,其实就是把trait类中的代码复制到类中使用

trait优先级的问题

1、当前类中的方法与trait类,父类中的方法重名了,怎么办?

2、trait类的优先级是高于同名父类

3、当多个triat类中有同名的方法,怎么办?

可以给不同的方法取一个别名

use Demo1,Demo2{

Demo1::hello as Demo1Hello;

}

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!