PHP implements a method of code reuse, called trait

Source: Internet
Author: User

Since php 5.4.0 , PHP has implemented a code reuse method called trait.

Trait is a code reuse mechanism that is prepared for PHP-like single-inheritance languages. Trait to reduce the limitations of single-inheritance languages, developers are free to reuse method in separate classes within different hierarchies.

  Trait is a solution for PHP multiple inheritance . For example, it would be cumbersome to inherit two Abstract classes at the same time, Trait to solve the problem.

It adds a combination of horizontal features to traditional inheritance.

Example 1: Defining trait with the trait keyword

Trait first_trait{    publicfunction  hello () {        return ' Hello ' ;    }}

Example 2: Using Trait in class, using the Use keyword, separated by commas when using multiple trait

Trait first_trait{ Public functionHello () {return' Hello '; }}trait second_trait{ Public functionWorld () {return' World '; }}classfirst_class{ UseFirst_trait,second_trait;}$obj=NewFirst_class ();Echo $obj-hello ();Echo $obj->world ();

Example 3: Priority

Members that inherit from the base class are overwritten by the members that are inserted by trait. Precedence is the method from which the member of the current class overrides the trait, and trait overrides the inherited method.

Example: A member inherited from a base class is overwritten by a member inserted by trait

classBase { Public functionSayHello () {Echo' Hello '; }}trait Sayworld { Public functionSayHello () {Parent::SayHello (); Echo' world! '; }}classMyhelloworldextendsBase { UseSayworld;}$o=NewMyhelloworld ();$o-SayHello ();//results of the outputHello world!

Example: the member of the current class overrides the Trait method

trait HelloWorld { Public functionSayHello () {Echo' Hello world! '; }}classTheworldisnotenough { UseHelloWorld;  Public functionSayHello () {Echo' Hello universe! '; }}$o=NewTheworldisnotenough ();$o-SayHello ();//results of the outputHello universe!

Example of nesting between 4:trait

Trait first_trait{ Public functionHello () {Echo' Hello '; }}trait second_trait{//nesting between trait     Usefirst_trait;  Public functionWorld () {Echo' World '; }}classfirst_class{ Usesecond_trait;}$obj=NewFirst_class ();Echo $obj-hello ();Echo $obj->world ();

Example 5: You can declare an abstract method in trait, use its class or trait to implement an abstract method

Trait first_trait{ Public functionHello () {Echo' Hello '; }    //Abstract Methods     Public Abstract functiontest ();} Trait second_trait{//nesting between trait     Usefirst_trait;  Public functionWorld () {Echo' World '; }    //implementing the test method in First_trait     Public functionTest () {Echo‘!‘; }}classfirst_class{ Usesecond_trait;}$obj=NewFirst_class ();Echo $obj-hello ();Echo $obj-World ();Echo $obj-test ();//will outputhelloworld!

Example 6: conflict resolution

If two trait all insert a method with the same name , a fatal error will occur if the conflict is not resolved explicitly.

In order to resolve the naming conflicts of multiple trait in the same class, it is necessary to use the insteadof operator to explicitly specify which of the conflicting methods to use.

The above method only allows other methods to be excluded, as operator can introduce one of the conflicting methods to another name, equivalent to the alias of the method .

trait A { Public functionSmallTalk () {EchoA; }     Public functionBigtalk () {EchoA; }}trait B { Public functionSmallTalk () {Echo' B '; }     Public functionBigtalk () {EchoB; }}classTalker { UseAB {b:: SmallTalk insteadof A;//the Smalltalk method of trait B replaces the Smalltalk method of trait AA::bigtalk insteadof B;//the Bigtalk method of trait a replaces the Bigtalk method of trait B    }}classAliased_talker { UseAB {b:: SmallTalk insteadof A;//the Smalltalk method of trait B replaces the Smalltalk method of trait AA::bigtalk insteadof B;//the Bigtalk method of trait a replaces the Bigtalk method of trait BB::bigtalk asTalk//use the AS operator to define the talk method as an alias for the Bigtalk method of B    }}$obj=NewTalker ();$obj-SmallTalk ();$obj-Bigtalk ();//The result is the output of BA$obj 2=NewAliased_talker ();$obj 2->talk ();//will output B

Example 7: Modify access control for a method

trait HelloWorld { Public functionSayHello () {Echo' Hello world! '; }}//Modify access control for SayHelloclassMyClass1 { UseHelloWorld {SayHello as protected; }}//give the method a change in Access control alias//original SayHello access control is not changedclassMyClass2 { UseHelloWorld {SayHello as PrivateMyprivatehello;}}

Example 8:trait can also define attributes

trait propertiestrait {    public$x = 1;} class propertiesexample {    use  propertiestrait;} $example New propertiesexample; $example->x;

If trait defines an attribute, the class will not be able to define a property of the same name, or an error will result. If the attribute's definition in the class is compatible with the definition in trait (the same visibility and initial value) then the error level is E_STRICT , otherwise it is a fatal error.

trait propertiestrait { Public $same=true;  Public $different=false;}classPropertiesexample { Usepropertiestrait;  Public $same=true;//Strict Standards     Public $different=true;//Fatal error}

If you have read this article for a while, please give me the top one , if the article has the wrong place, welcome to point out.

Learn from each other and make progress together!

PHP implements a method of code reuse, called trait

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.