PHP implements a code reuse method called trait, multiplexing trait_php tutorial

Source: Internet
Author: User

PHP implements a code reuse method called trait, multiplexing trait


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{    publicfunction  hello () {        return ' Hello ' ;    }} Trait second_trait{    publicfunction World () {        return ' World ';    }} class first_class{    use first_trait,second_trait;}  $obj=new  first_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

class Base {    publicfunction  SayHello () {        echo ' Hello ';    }} Trait Sayworld {    publicfunction  SayHello () {        parent::SayHello ();         Echo ' world! ' ;    }} class extends Base {    use  sayworld;} $o New Myhelloworld (); $o-SayHello (); // results of the output Hello world!

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

trait HelloWorld {    publicfunction  SayHello () {        echo ' Hello world! ' ;    }} class Theworldisnotenough {    use  HelloWorld;      Public function SayHello () {        echo ' Hello universe! ' ;    }} $o New Theworldisnotenough (); $o-SayHello (); // results of the output Hello universe!

Example of nesting between 4:trait

Trait first_trait{    publicfunction  hello () {        echo ' Hello ';    }} Trait nested    use first_trait between second_trait{//trait      ;      Public function World () {        echo ' World ';    }} class first_class{    use  second_trait;} $obj=new  first_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 {    publicfunction  SayHello () {        echo ' Hello world! ' ;    }} // Modify access control for SayHello class MyClass1 {    use asprotected;}} // give the method a change in Access control alias//original SayHello access control is not changed class MyClass2 {    use asprivate  Myprivatehello;}}

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$sametrue;      Public $different false ;} class propertiesexample {    use  propertiestrait;      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!

http://www.bkjia.com/PHPjc/1122395.html www.bkjia.com true http://www.bkjia.com/PHPjc/1122395.html techarticle PHP implements a code reuse method called trait, multiplexed trait from PHP 5.4.0, PHP implements a code reuse method called trait. Trait is for PHP-like single-relay ...

  • Related Article

    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.