Originally from: http://www.cnblogs.com/thinksasa/archive/2013/05/16/3081247.html
PHP 5.4 In the traits, is the newly introduced features, Chinese really do not know how to accurately translate good. Its actual purpose is for some occasions to want to use multiple inheritance, but PHP did not inherit much , so the invention of 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! cannot be instantiated. The first example looks at the syntax:
<?phptrait mytrait{ function TraitMethod1 () {} function traitMethod2 () {}}//Then call this traits, the syntax is: class myclass{use mytrait;} This allows you to invoke the method in traits using the use Mytraits, for example: $obj = new MyClass (), $obj-traitMethod1 (), $obj-traitMethod2 (); >
Next, let's explore why use traits, for example, there are two classes, business (commercial) and individual (individual), they all have address properties, the traditional practice is to abstract a class of these two have common attributes of the parent class, such as the client , set the access properties in the client class address,business and individual, respectively, with the following code:
Class client class client { private $address; Public getaddress () { return $this->address; } Public Setaddress ($address) { $this->address = $address; } } Class Business extends client{// You can use the Address property } //class individual class individual extends client{ //The Address property can be used here }
But what if there is another one called the order class that needs to access the same address attribute? The Order class is not able to inherit from the client class because it does not conform to OOP principles. This time traits comes in handy, you can define a traits to define these public properties.
Trait addresstrait address{ private $address; Public getaddress () { eturn $this->address; } Public Setaddress ($address) { $this->address = $address; }} Class businessclass business{use Address; The address attribute can be used here}//Class Individualclass individual{use address; The address attribute can be used here}//Class Orderclass order{use address; The Address property can be used here}
It's a lot easier!
Ext: PHP 5.4 in traits