PHP traits simple use instance, phptraits instance
Traits in PHP 5.4 is a newly introduced feature. Chinese really do not know how to translate well. 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:
<? Phptrait myTrait {function traitMethod1 () {} function traitMethod2 () {}} // then call this traits. Syntax: class myClass {use myTrait ;} // you can use myTraits to call the methods in Traits, for example, $ obj = new myClass (); $ obj-> traitMethod1 (); $ obj-> traitMethod2 ();>
Next, let's explore why we need to use traits. For example, there are two classes: business (business) and Individual (Individual). They both have the address attribute, 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, business, and individual to inherit from each other, 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 Individual class Individual 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 Individualclass Individual {use Address; // here the address attribute can be used} // Class Orderclass Order {use Address; // here the address attribute can be used}
This is much more convenient!