Home > Article > Backend Development > Simple examples of using traits in PHP_PHP tutorial
This article mainly introduces a simple example of using traits in PHP. This article focuses on the syntax of traits, what functions traits have, and what situations they are. Use traits below, friends in need can refer to it
Traits in PHP 5.4 is a newly introduced feature. I really don’t know how to translate it accurately into Chinese. Its actual purpose is to use multiple inheritance in some situations, but PHP does not have multiple inheritance, so such a thing was invented.
Traits can be understood as a set of methods that can be called by different classes, but Traits are not classes! They cannot be instantiated. Let’s take an example to look at the syntax first:
?
2 3
|
<🎜>trait myTrait{<🎜> <🎜>function traitMethod1(){}<🎜> <🎜>function traitMethod2(){}<🎜> <🎜> <🎜> <🎜>}<🎜> <🎜> <🎜> <🎜>//Then call this traits, the syntax is: <🎜> <🎜>class myClass{<🎜> <🎜>use myTrait;<🎜> <🎜>}<🎜> <🎜> <🎜> <🎜>//In this way, you can call the methods in Traits through use myTraits, such as: <🎜> <🎜>$obj = new myClass();<🎜> <🎜>$obj-> traitMethod1 (); $obj-> traitMethod2 (); > |
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 there is another class called order that needs to access the same address attribute? The order class cannot inherit the client class because this does not comply with the OOP principle. Traits come in handy at this time. You can define a trait to define these public properties.
?
2 3 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 } |