当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP的Trait机制原理与用法分析

PHP的Trait机制原理与用法分析

2020年03月09日  | 移动技术网IT编程  | 我要评论

克里姆林宫的狼人,wwe2013最新赛事,夏天里的雪

本文实例讲述了php的trait机制原理与用法。分享给大家供大家参考,具体如下:

trait介绍:

1、自php5.4起,php实现了一种代码复用的方法,称为trait。
2、trait是为类似php的单继承语言二准备的一种代码复用机制。
3、trait为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用method。
4、trait实现了代码的复用,突破了单继承的限制;
5、trait是类,但是不能实例化。
6、当类中方法重名时,优先级,当前类>trait>父类;
7、当多个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 "
"; echo $cls->test1(); echo "
"; 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 "
"; echo $cls->test2();

运行结果:

demo1::test
demo2::test

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网