Traits simple usage examples in PHP
This article mainly introduced the PHP traits simple Use example, this article emphatically explains traits's grammar, traits has what function, under what situation uses the traits, the need friend can refer to the next
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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Trait mytrait{ function TraitMethod1 () {} function TraitMethod2 () {} } Then it is called 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:
?
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{ You can use the Address property here } Class Individual Class individual extends client{ You can use the Address property here } |
But what if there is another order class that needs to access the same address attribute? The Order class is not able to inherit from the client class, because this does not conform to the principles of OOP. This time traits comes in handy, you can define a traits to define these public properties.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 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; You can use the Address property here } Class Individual Class individual{ Use Address; You can use the Address property here } Class Order Class order{ Use Address; You can use the Address property here } |
It's a lot easier!
http://www.bkjia.com/PHPjc/1000096.html www.bkjia.com true http://www.bkjia.com/PHPjc/1000096.html techarticle php Traits Simple Use examples this article mainly introduces the PHP traits simple use examples, this article focuses on traits syntax, traits what role, under what circumstances use Trai ...