Home >Backend Development >PHP Tutorial >Analyze the principles and usage of Trait mechanism in PHP

Analyze the principles and usage of Trait mechanism in PHP

青灯夜游
青灯夜游forward
2020-04-23 09:19:363027browse

This article will analyze the principles and usage of the Trait mechanism in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Analyze the principles and usage of Trait mechanism in PHP

Trait introduction:

1. Since PHP5.4, PHP has implemented a code reuse method called for trait.

2. Trait is a code reuse mechanism prepared for single inheritance languages ​​​​like PHP.

3. In order to reduce the restrictions of single inheritance language, Trait allows developers to freely reuse methods in independent classes in different hierarchies.

4. Trait realizes code reuse and breaks through the limitation of single inheritance;

5. Trait is a class, but it cannot be instantiated.

6. When the methods in the class have the same name, the priority is: current class>trait>parent class;

7. When the methods of multiple trait classes have the same name, you need to specify the access Which, aliases other methods.

Example:

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();

Run result:

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

Multiple trait methods have the same name:

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();

Run result:

Demo1::test
Demo2::test

For more related knowledge, please pay attention to PHP Chinese website! !

The above is the detailed content of Analyze the principles and usage of Trait mechanism in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete