The function of php traits is designed for single inheritance languages such as php. It is designed to allow developers to easily share a series of methods between multiple classes in different inheritance systems to reduce the problems caused by single inheritance. limitations.
Traits
is designed for single inheritance languages like php. It is designed to allow developers to easily share a series of methods between multiple classes in different inheritance systems to reduce the limitations caused by single inheritance. The combination of traits and classes avoids a series of problems caused by multiple inheritance.
Using
First look at the example given in the official document:
<?php trait ezcReflectionReturnInfo { function getReturnType() { /*1*/ } function getReturnDescription() { /*2*/ } } class ezcReflectionMethod extends ReflectionMethod { use ezcReflectionReturnInfo; /* ... */ } class ezcReflectionFunction extends ReflectionFunction { use ezcReflectionReturnInfo; /* ... */ } ?>
As can be seen from the above example, the feature set ezcReflectionReturnInfo
contains two Methods: getReturnType
and getReturnDescription
, and the following two subclasses inherit from different parent classes, but they can be reused by use ezcReflectionReturnInfo
method. easy and convenient.
Related learning recommendations: PHP programming from entry to proficiency
Notes
If there are methods with the same name in the traits of the subclass, parent class, and use, then the priority of these three methods is: subclass> tratis > parent class;
You can use multiple traits at the same time, but you cannot use traits with the same name;
If there is a method name conflict in multiple traits used, you can use to specify a method from a certain A trait. For example:
<?php trait A { public function smallTalk() { echo 'a'; } public function bigTalk() { echo 'A'; } } trait B { public function smallTalk() { echo 'b'; } public function bigTalk() { echo 'B'; } } class Talker { use A, B { B::smallTalk insteadof A; A::bigTalk insteadof B; } }
The method can use as to set the alias, but it is only valid in this class.
class Aliased_Talker { use A, B { B::smallTalk insteadof A; A::bigTalk insteadof B; B::bigTalk as talk; } }
When using as, you can also change the visibility of the method.
class MyClass2 { use HelloWorld { sayHello as private myPrivateHello; } }
traits can be nested, for example, A can use B.
<?php trait Hello { public function sayHello() { echo 'Hello '; } } trait World { public function sayWorld() { echo 'World!'; } } trait HelloWorld { use Hello, World; }
Traits can define abstract methods. Similarly, the class that uses the traits also needs to implement these abstract methods;
Conventional variables, static variables and methods can be defined in traits;
The above is the detailed content of What are the functions of php traits?. For more information, please follow other related articles on the PHP Chinese website!