http://php.net/manual/en/language.oop5.traits.php
Since PHP5.4.0, PHP has implemented a method of code reuse, called Traints.
Traits is a code reuse mechanism that is prepared for PHP-like single-inheritance speech. Trait to reduce the limitations of single-inheritance statements, developers are free to reuse the set of methods in separate classes within different hierarchies. The semantics of traits and class combinations is to define a method to reduce complexity and avoid typical problems associated with traditional inheritance and mixing classes (Mixin).
Traits is similar to a class, but only designed to combine functionality in a fine-grained and one-way manner. Trait cannot be instantiated by itself. It adds a combination of horizontal attributes to traditional inheritance, meaning that members of the application class do not need inheritance.
In my understanding, it is in the inheritance class chain that the subclass inherits some of the attributes of the parent class (that is, when the subclass "wants to use the attributes of the parent class", if trait has one, the trait method, the property, and so on) is isolated.
Var. Php_eol; } function A () { echo "a". Php_eol;} } Interface myinterface{ function __construct (); function B ();} Abstract class myabstract{ protected $var 2 = "Myabstract_var"; Use mytrait; Function B () { echo "B". Php_eol;} } Class MyClass extends Myabstract implements myinterface{ protected $var 3 = "Myclass_var"; can also be referenced here, do not distinguish between the inheritance relationship //use mytrait function C () { echo "C". Php_eol;} } $class = new MyClass (); $class->a (); $class->b (); $class->c ();
Output Result:
Summary :
① Essentially, the concept of trait and include files is almost
②trait can be more convenient for code reuse, because we implement the private property and method of the subclass in the parent class, and the trait is the same as the effect of writing the code directly in the object.
③ when using trait, you should resolutely avoid naming conflicts, especially when using multiple trait at the same time.
④ If a naming conflict arises, if the visibility, initial value, or static of the two are exactly the same, the trait will overwrite the object and throw a e_strict error, otherwise it will throw a e_compile_error error and terminate the compilation.