Traits Learning
More and more frameworks and code are beginning to use the traits way to organize some functions, which is very efficient code organization structure.
Use trait to reduce unnecessary class inheritance and make your code more reusable, creating a collection of code that you can plug in.
Separated by commas, multiple trait are listed in the use declaration and can be inserted into a class.
An example of a single:
<?phptrait Seller{ public function sell() { print_r("sell all goods"); } }class MySeller{ use Seller; }$seller = new MySeller();$seller->sell();
Examples of multiple trait:
<?phpTrait money{PublicfunctionShow() {Echo "200$";}} trait factory{public function run () {Print_r (" running All "); }}class user{ use money, Factory; public function Show () {echo "I am an user";} $user = new User (); $user->show (); //= I am an user
When the class that introduces trait also has a method or function of the same name, the method of the current class overrides the same name method in trait.
As in the example above, both the user class and the money trait have a show method, the user class's show method is called after execution, and the content of "I am an User" is printed.
However, if two trait all insert a method with the same name, a fatal error will occur if the conflict is not resolved explicitly. We need to explicitly specify whether a trait method or try not to have the same name method in different trait.
1. Use the INSTEADOF operator to explicitly specify which of the conflicting methods to use. For example:
<?phpTrait token{PublicfunctionTostring($var) {The return (string) $var."_token"; }PublicfunctionTips() {Print_r ("Token tips!"); }}Trait tester{PublicfunctionTostring($var) {return (String) $var. "_test";} public function tips" Tester tips ");}} class controller{use token, tester {Token :: tostring insteadof Tester; Tester::tips insteadof Token;} $con = new Controller (), $con->tostring ( ' hello '); $con Tips ( ' my god! ');
Or use aliases to avoid problems with the same name, such as:
class Controller{ user Token, Tester { Token::toString as toTokenString; Tester::tips as testerTips; }}
These are some of the theoretical cases, in fact some high-quality and modern PHP frameworks are already using the trait way to organize the entire code. The typical is laravel. such as/www/larblog/app/http/controllers/controller.php:
<?phpNamespaceApp\Http\Controllers;UseIlluminate\foundation\Bus\Dispatchesjobs;UseIlluminate\routing\ControllerAsBasecontroller;UseIlluminate\foundation\validation\validatesrequests; use illuminate\Foundation\auth\access\authorizesrequests;use illuminate\foundation\ auth\access\AuthorizesResources;< Span class= "Hljs-class" >class controller extends basecontroller{use authorizesrequests, authorizesresources, Dispatchesjobs, validatesrequests;}
Four trait are used here.
Traits Learning notes in PHP