PHP Learning--traits new features, php--traits new features _php tutorials

Source: Internet
Author: User
Tags traits

PHP Learning--traits new features, php--traits new features


In the reading Yii2 source of contact with the trait, learn a bit, write down the blog record.

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/*1* / }      function/*2* *  }}classextends  Reflectionmethod {    use  ezcreflectionreturninfo;     /*  */}classextends  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 {    publicfunction  SayHello () {        echo ') Hello ';    }} Trait Sayworld {    publicfunction  SayHello () {        parent::  SayHello ();         Echo ' world! ' ;    }} class 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 {    publicfunction  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 Instea        DOF A;    A ::  bigtalk insteadof B; }}   class   aliased_talker {  use  A,  b {b ::  smalltal        K 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 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;}}? >

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 {    publicfunction  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$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 $o // Echo 1 $p New $p // Echo 1?>

Examples of static methods

 
  Phptrait staticexample {public    staticfunction  dosomething () {          Return ' Doing something ';    }} class Example {    use  staticexample;} Example::dosomething ();? >

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//  echo 1//  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    $sametrue;      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__  php_eol;         Echo Php_eol ;    }} class BaseClass {    use  testtrait;} class 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 functiongetinstance () {Static $_instance=NULL; $class=__class__; return $_instance?:$_instance=New $class; }         Public function__clone () {Trigger_error(' Cloning '.__class__. ' is not allowed. ',E_user_error); }         Public function__wakeup () {Trigger_error(' unserializing '.__class__. ' is not allowed. ',E_user_error); }}/** * Example Usage*/classFoo { UseSingleton; Private function__construct () {$this->name = ' foo '; }}classBar { UseSingleton; 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"?>

http://www.bkjia.com/PHPjc/927470.html www.bkjia.com true http://www.bkjia.com/PHPjc/927470.html techarticle PHP Learning--traits new features, php--traits new features in the reading Yii2 source of contact with the trait, learning a bit, write down a blog record. PHP has been implemented since PHP 5.4.0 .

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