Parsing of trait in PHP

Source: Internet
Author: User
Tags traits
This article mainly introduces the trait of PHP in the analysis, has a certain reference value, now share to everyone, the need for friends can refer to

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

Trait it literally means "features", "features", we can understand that using the TRAIT keyword, you can add new features to the classes in PHP.

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. The semantics of Trait and class combinations define a way to reduce complexity, avoiding traditional multi-inheritance and Mixin class-related typical problems.

Trait is similar to Class, but only designed to combine functionality in a fine-grained and consistent way. cannot be instantiated by trait itself. It adds a combination of horizontal features to the traditional inheritance, meaning that no inheritance is required between several classes of the application.

Usage: By using the USE keyword in the class, declare the trait name to be combined, the specific trait declaration uses the Trait keyword, trait cannot be instantiated.

1, Traits Foundation

<?phpheader ("Content-type:text/html;charset=utf-8"); Trait Test{public function Hello1 () {        return "Test:: Hello1 () ";    }} Class demo1{use    Test;} $obj = new Demo1 (); Echo $obj->hello1 (). ' <br/> ';//test::hello1 ()

2. Priority level

<?phpclass Base {public    function SayHello () {        echo ' Hello ';    }} Trait Sayworld {public    function SayHello () {        Parent::sayhello ();                Echo ' world! ';    }} Class Myhelloworld extends Base {use    Sayworld;} $o = new Myhelloworld (); $o->sayhello ();//hello world!

<?phptrait HelloWorld {public    function SayHello () {        echo ' Hello world! ';    }} Class Theworldisnotenough {use    HelloWorld;    Public Function SayHello () {        echo ' Hello universe! ';    }} $o = new Theworldisnotenough (); $o->sayhello ();//hello universe!

Members inherited from the base class are overwritten by the Myhelloworld method in the inserted Sayworld Trait. Its behavior is consistent with the methods defined in the Myhelloworld class. The precedence is that methods in the current class override the Trait method, and the trait method overrides the method in the base class.

3, multiple traits

Separated by commas, multiple trait are listed in the use declaration and can be inserted into a class.

<?phptrait Hello {public    function SayHello () {        echo ' hello '. <br/> ';    }} Trait World {public    function Sayworld () {        echo ' world '. <br/> ';    }} Class Myhelloworld {Use    Hello, world;    Public Function Sayexclamationmark () {        echo '! '. ' <br/> ';    }} $o = new Myhelloworld (); $o->sayhello ();//hello$o->sayworld ();//world$o->sayexclamationmark ();//!

4. 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.

<?phptrait a{public    function SmallTalk () {        echo ' A ';    }    Public Function Bigtalk () {        echo ' A ';    }} Trait b{public    function SmallTalk () {        echo ' B ';    }    Public Function Bigtalk () {        echo ' B ';    }} Class talker{use    a,b{        b::smalltalk insteadof A;        A::bigtalk insteadof B;    }} $obj = new Talker (); $obj->smalltalk ();//b$obj->bigtalk ();//a

The above method only allows the exclusion of other methods, and the as operator can introduce aliases for a method. Note that the as operator does not rename the method, nor does it affect its methods.

<?phptrait a{public    function SmallTalk () {        echo ' A ';    }    Public Function Bigtalk () {        echo ' A ';    }} Trait b{public    function SmallTalk () {        echo ' B ';    }    Public Function Bigtalk () {        echo ' B ';    }} Class talker{use    a,b{        b::smalltalk insteadof A;        A::bigtalk insteadof B;        B::bigtalk as B_bigtalk;        A::smalltalk as A_smalltalk;    }} $obj = new Talker (); $obj->smalltalk ();//b$obj->bigtalk ();//a$obj->b_bigtalk ();//b$obj->a_smalltalk () ;//a

5. Access control of modified method

Using The AS syntax can also be used to adjust the access control of a method.

<?phptrait a{    Private Function SmallTalk () {        echo ' A ';    }} Class talker{use    a{        smallTalk as public aaa;    }} $obj = new Talker (); $obj->aaa ();//a

6. Traits Group

Just as class can use trait, other trait can also use trait. By using one or more trait when trait is defined, you can combine some or all of the members of another trait.

<?phptrait hello{public    function SayHello () {        echo ' Hello ';    }} Trait world{public    function Sayworld () {        echo ' world! ';    }} Trait helloworld{use    hello,world;} Class talker{use    HelloWorld;} $obj = new Talker (); $obj->sayhello ();//hello$obj->sayworld ();//world!

7. Abstract members

In order to impose mandatory requirements on the classes used, trait supports the use of abstract methods.

<?phptrait hello{public    function Sayworld () {        echo ' Hello '. $this->getworld ();    }    Abstract public Function Getworld ();} Class talker{    private $world;    Use Hello;    Public Function Getworld () {        return $this->world;    }    Public Function Setworld ($val) {        $this->world = $val;    }} $obj = new Talker (); $obj->setworld ("Trait!"); $obj->sayworld ();//hello Trait!

8. Traits static Members

Traits can be defined by static member static methods.

<?phptrait helloworld{public    static function SayHelloWorld () {        echo ' Hello world! ';    }} Class talker{use    HelloWorld;} Talker::sayhelloworld ();//hello world!

<?phptrait counter{Public    Function Inc () {        static $c = 0;        $c + +;        echo "$c \ n";    }} Class c1{use    Counter;} Class c2{use    Counter;} $c 1 = new C1 (), $c 1->inc ();//1$c1_1 = new C1 (); $c 1_1->inc ();//2$c2 = new C2 (); $c 2->inc ();//1

9. Properties

Trait can also define attributes.

<?phptrait propertiestrait {public    $x = 1;} Class Propertiesexample {use    propertiestrait;} $example = new Propertiesexample;echo $example->X;//1

Trait A property is defined, the class cannot define a property of the same name, otherwise it will produce fatal error. There is an exception: the property is compatible (same access visibility, initial default value). Prior to PHP 7.0, the properties were compatible and there would be e_strict reminders.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.