Simple use of traits in PHP. Simple use of traits in PHP this article mainly introduces simple use of traits in PHP, this article focuses on the traits syntax, the role of traits, and the simple use of traits in trai PHP.
This article describes the simple use of traits in PHP. This article focuses on the traits syntax, the role of traits, and the use of traits. For more information, see
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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Trait myTrait { Function traitMethod1 (){} Function traitMethod2 (){} } // Then call this traits. The syntax is: 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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Class Client Class Client { Private $ address; Public getAddress (){ Return $ this-> address; } Public setAddress ($ address ){ $ This-> address = $ address; } } Class Business extends Client { // The address attribute can be used here } // Class Inpidual Class Inpidual extends Client { // The address attribute can be used here } |
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.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Trait Address Trait Address { Private $ address; Public getAddress (){ Eturn $ this-> address; } Public setAddress ($ address ){ $ This-> address = $ address; } } // Class Business Class Business { Use Address; // The address attribute can be used here } // Class Inpidual Class Inpidual { Use Address; // The address attribute can be used here } // Class Order Class Order { Use Address; // The address attribute can be used here } |
This is much more convenient!
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 trai is used...