This article mainly introduces the simple use of traits in PHP. This article focuses on the traits syntax, what role does traits play, and when traits is used, for more information, see traits in PHP 5.4. it 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:
<? 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 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}
This is much more convenient!