Simple use of traits in 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 |
<? Php 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 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:
?
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 Individual Class Individual 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 Individual Class Individual { 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!