Turn: PHP 5.4 in traits

Original link: http://www.cnblogs.com/guoyongrong/p/3958749.html

Original from: http: //www.cnblogs.com/thinksasa/archive/2013/05/16/3081247.html

PHP 5.4 in traits, is characteristic of the newly introduced Chinese really do not know how to accurately translate well. Its real purpose is to want to inherit some occasions with many, but not any PHP multiple inheritance , so he invented such a thing.
       Traits can be understood as a set of different classes can call to the set of methods , but not Traits class! It can not be instantiated. Examples of the first to look at the syntax:

Copy the code
<?php
{related myTrait
    function traitMethod1(){}
    function traitMethod2(){}

}

// then call the traits, the syntax is:
class myClass{
    use myTrait;
}

// so that you can use myTraits, call the method Traits, such as:
$obj = new myClass();
$obj-> traitMethod1 ();
$obj-> traitMethod2 (); 
>
Copy the code

  Next, we explore why the next use traits, for example, for example, there are two categories, namely business (business person) and Individual (personal), they have the property address, the traditional approach is a further abstraction both classes have a common parent class has properties, such as client, the access attribute set in the client address class, and Business individual succession, respectively, the following code:

Copy the code
// Class Client  
class Client  {  
    private $address;  
    public getAddress() {  
        return $this->address;  
    }       
    public setAddress($address) {  
        $this->address = $address;    
    }  
}  
      
class Business extends Client{  
    // Here you can use the address attribute  
}  

// Class Individual  
class Individual extends Client{  
// Here you can use the address attribute  
}  
Copy the code

  But if there's a class called order, need access to the same address of the property, how to do it? order category is no way to inherit client class, because this does not meet the principles of OOP. This time traits come in handy, you can define a traits, used to define these public properties.

Copy the code
// Trait Address
trait Address{
    private $address;
    public getAddress() {
        eturn $this->address;
    }
    public setAddress($address) {
        $this->address = $address;
    }
}
// Class Business
class Business{
    use Address;
    // Here you can use the address attribute
}
// Class Individual
class Individual{
    use Address;
    // Here you can use the address attribute
}
// Class Order
class Order{
    use Address;
    // Here you can use the address attribute
}     
Copy the code

So much more convenient!

Reproduced in: https: //www.cnblogs.com/guoyongrong/p/3958749.html

Guess you like

Origin blog.csdn.net/weixin_30815469/article/details/94794198
5.4