Traits in PHP54 is a newly introduced feature. Chinese really do not know how to translate it accurately. The actual purpose is to use multi-inheritance for some occasions, but PHP does not have many Inheritance. Therefore, traits in PHP 5.4 is a newly introduced feature, I really don't know how to translate Chinese. The actual purpose is to use multi-inheritance for some occasions, but PHP does not inherit much, so it invented such a thing.
Traits can be understood as a set of methods that can be called by different classes, but Traits is not a class! It cannot be instantiated. Let's take an example to see the syntax:
TraitMethod1 (); $ obj-> traitMethod2 ();
Next, let's explore why traits should be used. for example, there are two classes: business (business) and Inpidual (personal). they both have the attribute of the address, the traditional approach is to abstract a parent class with features of both classes, such as the client. in the client class, set the access attribute address, and inherit the business and inpidual respectively, the following code:
// Class Client class Client {private $ address; public getAddress () {return $ this-> address;} public setAddress ($ address) {$ this-> address = $ address ;}} class Business extends Client {// Here you can use the address attribute} // Class Inpidual class Inpidual extends Client {// Here you can use the address attribute}
But what if another one is called the order class and needs to access the same address attribute? The order class cannot inherit the client class because it does not conform to the OOP principle. In this case, traits can be used to define public attributes.
// Trait Addresstrait Address {private $ address; public getAddress () {eturn $ this-> address;} public setAddress ($ address) {$ this-> address = $ address ;}// Class Businessclass Business {use Address; // you can use the address attribute here} // Class Inpidualclass Inpidual {use Address; // here the address attribute can be used} // Class Orderclass Order {use Address; // here the address attribute can be used}