This article is about PHP traits properties and basic usage, now share to everyone, the need for friends can refer to
First, what is traits
PHP 5.4, traits, is the newly introduced feature, and its practical purpose is to solve the single-inheritance Problem of PHP, the method used to implement code reuse.
Traits can be understood as a set of methods that can be called by different classes, but traits is not a class! cannot be instantiated.
PHP is a single-inheritance language, and we can't extends multiple base classes in a class like Java to implement code reuse, and now traits can solve the problem of code reuse, which allows developers to implement code reuse in a variety of classes.
Traits and class are defined in semantics to reduce the complexity of the code and avoid multiple inheritance problems.
Second, the characteristics of traits
1. Example Reference link:
https://segmentfault.com/a/1190000002970128
2. Features reference link:
https://blog.csdn.net/longlongmylove/article/details/7521379
3. Inheritance vs polymorphism vs Trait
Reference Link: http://www.jb51.net/article/105579.htm
Third, the use of traits in Laravel
The words always feel that the use of laravel in the aspect, can directly call the method of encapsulation class. See a blogger's article today, only to know that Laravel has used a lot of traits features.
Summary: 1, trait is essentially a Class 2, interface (interface) defines the definition of the method, trait stipulates the implementation of the method 3, you can think of Class A D and other classes in the need for the CCC method is included in the trait
In conclusion, trait is a kind of compromise method that PHP implements multiple inheritance, call it "false multiple inheritance", can consider a class (Class A) contains another class E (trait), the ultimate goal is to implement code reuse.
Reference Link: https://zhuanlan.zhihu.com/p/31154445
Generally speaking, the appearance of traits greatly facilitates our development, after all, can not be more inheritance is really inconvenient, especially for large projects. Even just "pseudo-inheritance" is better than nothing. Many predecessors have summed up the already very in place, my side just is equivalent to take a note.
End