New features of PHP learning--traits

Source: Internet
Author: User
Tags traits

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

Traits 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 the set of methods in separate classes within different hierarchies. The semantics of Traits and class combinations are defined as a way to reduce complexity and avoid typical problems associated with traditional multi-inheritance and mixed-Class (Mixin).

Trait is similar to a class, but only designed to combine functionality in a fine-grained and consistent way. Trait cannot be instantiated by itself. It adds a combination of horizontal attributes to traditional inheritance, meaning that members of the application class do not need inheritance.

Trait Example

<?phptrait Ezcreflectionreturninfo {    function Getreturntype () {/*1*/}    function Getreturndescription () {/* 2*/}}class Ezcreflectionmethod extends Reflectionmethod {use    ezcreflectionreturninfo;    /* */}class Ezcreflectionfunction extends Reflectionfunction {use    ezcreflectionreturninfo;    /* ... */}?>
Priority level

A member inherited from a base class is overwritten by a member 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 of precedence order

<?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 ();? >

The above routines will output: Hello world!

Members inherited from the base class are overwritten by the SayHello 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.

Another example of priority order

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

The above routines will output: Hello universe!

Multiple trait

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

Examples of the use of multiple trait

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

The above routines will output: Hello world!

Resolution of conflicts

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, and the as operator can introduce one of the conflicting methods with another name.

Examples of conflict resolution

<?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;    }} Class Aliased_talker {Use    A, B {        b::smalltalk insteadof A;        A::bigtalk insteadof B;        B::bigtalk as Talk;    }}? >

In this example, Talker uses trait A and B. Because A and B have conflicting methods, they define the use of smallTalk in trait B and the bigtalk in trait a.

Aliased_talker uses the as operator to define talk as an alias for the bigtalk of B.

Modify access control for a method

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

Example of modifying access control for a method

<?phptrait HelloWorld {public    function SayHello () {        echo ' Hello world! ';    }} Modify SayHello access Control class MyClass1 {use    HelloWorld {SayHello as protected;}} Give method a changed access control alias//original SayHello access control is not changed class MyClass2 {use    HelloWorld {SayHello as Private Myprivatehello;}} ?>
From trait to form trait

Just as classes can use trait, other trait can also use trait. When trait is defined, it can combine some or all of the members of another trait by using one or more trait.

Examples of trait from trait

<?phptrait Hello {public    function SayHello () {        echo ' hello ';    }} Trait World {public    function Sayworld () {        echo ' world! ';    }} Trait HelloWorld {Use    Hello, world;} Class Myhelloworld {use    HelloWorld;} $o = new Myhelloworld (); $o->sayhello (); $o->sayworld ();? >

The above routines will output: Hello world!

Abstract members of the Trait

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

An example of an abstract method to make a mandatory request

<?phptrait Hello {public    function SayHelloWorld () {        echo ' Hello '. $this->getworld ();    }    Abstract public Function Getworld ();} Class Myhelloworld {    private $world;    Use Hello;    Public Function Getworld () {        return $this->world;    }    Public Function Setworld ($val) {        $this->world = $val;    }}? >
Static members of the Trait

Traits can be defined by static member static methods.

Examples of static variables

<?phptrait Counter {public    Function Inc () {        static $c = 0;        $c = $c + 1;        echo "$c \ n";    }} Class C1 {use    Counter;} Class C2 {use    Counter;} $o = new C1 (); $o->inc (); echo 1$p = new C2 (); $p->inc (); Echo 1?>

Examples of static methods

<?phptrait staticexample {public    static function dosomething () {        return ' Doing something ';    }} Class Example {use    staticexample;} Example::d osomething ();? >

Examples of static variables and static methods

<?phptrait Counter {public    static $c = 0;    public Static Function Inc. () {self        :: $c = self:: $c + 1;        echo Self:: $c. "\ n";    }} Class C1 {use    Counter;} Class C2 {use    Counter;} C1::inc (); Echo 1c2::inc (); Echo 1?>
Property

Trait can also define attributes.

Examples of defining attributes

<?phptrait 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.

Examples of conflicts

<?phptrait propertiestrait {public    $same = true;    Public $different = false;} Class Propertiesexample {use    propertiestrait;    Public $same = true; Strict Standards Public    $different = true;//Fatal error}?>
The use of the different

Examples of different use

<?phpnamespace Foo\bar;use foo\test;  means \foo\test-the initial \ is Optional?><?phpnamespace foo\bar;class someclass {use    foo\test;   Means \foo\bar\foo\test}?>

The first use is used Foo\test for namespace, the \foo\test is found, the second uses is a trait, and the \foo\bar\foo\test is found.

__class__ and __trait__

__CLASS__ returns the CLASS name,__trait__ of Use trait returns trait name

Examples such as the following

<?phptrait testtrait {public    function TestMethod () {        echo "Class:". __class__. Php_eol;        echo "Trait:". __trait__. Php_eol;}    } Class BaseClass {use    testtrait;} Class TestClass extends BaseClass {} $t = new TestClass (); $t->testmethod ();//class:baseclass//trait:testtrait
Trait single case

Examples are as follows

<?phptrait Singleton {        /**     * Private construct, generally defined by using class     */    //private function __construct () {} public        static function getinstance () {        static $_instance = NULL;        $class = __class__;        Return $_instance?: $_instance = new $class;    }        Public Function __clone () {        trigger_error (' cloning '. __class__. ' are not allowed. ', e_user_error);    }        Public Function __wakeup () {        trigger_error (' unserializing '. __class__. ' are not allowed. ', e_user_error);    }} /*** Example usage*/class Foo {use    singleton;        Private Function __construct () {        $this->name = ' foo ';    }} Class Bar {use    singleton;        Private Function __construct () {        $this->name = ' bar ';    }} $foo = Foo::getinstance (), echo $foo->name; $bar = Bar::getinstance (); Echo $bar->name;
Calling the Trait method

Although not obvious, if the trait method can be defined as a static method in a normal class, it can be called

Examples are as follows

<?php trait Foo {     function bar () {         return ' Baz ';     }} Echo Foo::bar (), "\\n";?>

New features of PHP learning--traits

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.