This article mainly introduces the simple use of traits in PHP, this article focuses on traits grammar, traits what role, what the use of traits, the need for friends can refer to the
The traits in PHP 5.4 is a newly introduced feature, and Chinese really don't know how to translate it properly. The actual purpose is to want to use more inheritance for some occasions, but PHP did not inherit much, so it invented such a thing.
Traits can be understood as a set of methods that can be invoked by different classes, but traits is not a class! cannot be instantiated. Let's take a look at 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, syntax: class myclass{use mytrait; }//So you can invoke the method in traits by using mytraits, such as: $obj = new MyClass (); $obj-> traitMethod1 (); $obj-> traitMethod2 (); > |
Next, we explore why we should use traits, for example, there are two classes, business (business) and individual (individual), all of which have the attribute of the address, and the traditional approach is to abstract a parent class that has the same characteristics as the two classes, such as the client , set access properties address,business and individual in the client class, respectively, with 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 ($addr ESS) {$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 Of |
But what if there is an order class that needs access to the same address attribute? The Order class is not able to inherit the client class because it does not conform to OOP principles. This is when traits comes in handy, and you can define a traits to define these common properties.
?
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 The public getaddress () {Eturn $this->address;} public setaddress ($addr ESS) {$this->address = $address;}} Class Business class business{using Address;//Here you can use the address attribute}//class individual class individual{usage address; You can use the address attribute}//class Order class order{using address;//Here you can use the Address property} |
This is more convenient!