Traits usage

WBOY
Release: 2016-07-29 09:15:16
Original
1461 people have browsed it
Original source: http://blog.csdn.net/longlongmylove/article/details/7521379
Introduction to php5.4 new features Traits1. traits
Traits is a new addition in 5.4 Methods for implementing code reuse. php is a single inheritance language. We cannot extend multiple base classes in one class to achieve code reuse like Java. Now Traits can solve this code reuse problem. It allows developers to use multiple base classes in different classes. Implement code reuse in classes.
Traits and classes are semantically defined to reduce the complexity of the code and avoid the problem of multiple inheritance. Traits are similar to classes, but are only used to provide a set of functions in a unified and fine-grained manner. They cannot be instantiated inside Traits, that is, there is no class-like constructor __construct(). Traits acts as an extension of PHP's traditional inheritance and implements horizontal integration; therefore, inheritance is no longer needed in application classes. 1) How to use
Use the keyword 'use' to reference Traits in the class. Multiple Traits are separated by ','. The example code is as follows:

[php] view plaincopy

  1. trait ezcReflectionReturnInfo {
  2. function getReturnType() {
  3. }
  4. function getReturnDescription() {
  5. }
  6. }class ezcReflectionMethod extends ReflectionMethod {
  7. use ReflectionReturnInfo;
  8. /* ... */
  9. ) Info;
  10. /* ... */ }
  11. ?>
  12. 2) Priority Member functions in the base class will be overridden by functions in Traits, and member functions in the current class will override functions in Traits. [php] view plaincopy
    1. class Base {  
    2.     public function sayHello() {  
    3.         echo 'Hello ';  
    4.     }  
    5. }  
    6.   
    7. trait SayWorld {  
    8.     public function sayHello() {  
    9.         parent::sayHello();  
    10.         echo "World!n";  
    11.     }  
    12. }  
    13.   
    14. class MyHelloWorld extends Base {  
    15.     use SayWorld;  
    16. }  
    17.   
    18. class MyHelloWorldExt extends Base {  
    19.     use SayWorld;  
    20.     public function sayHello() {  
    21.         /**
    22. * Here are the new changes in 5.4. Versions before 5.4 will prompt:
    23. * PHP Cantal error: not use string offset as an array
    24.                                                Improved to return the character of the index number in the string
    25. ​​​*/  
    26.         $str  = "Arvin";  
    27.         echo $str[0][0];// echo 'A';  
    28.     }  
    29.   
    30.     public function shortArray() {  
    31.         $array = ['first', 2, 3, 4];//5.4中的数组简单语法  
    32.         echo $array[0];//5.4中的数组解引用取数组元素方法  
    33.     }  
    34. }  
    35.   
    36. $o = new MyHelloWorld();  
    37. $o->sayHello();  
    38. $oe = new MyHelloWorldExt();  
    39. $oe->sayHello();  
    40. echo "n";  
    41. $oe->shortArray();  

    [php] view plaincopy

    1. 输出:  
    2. Hello World!  
    3. A  
    4. first  
     3) Multiple TraitsMultiple Traits can be added to the declaration of a class, and multiple Traits are separated by ",".

    [php] view plaincopy

    1. trait Hello {
    2. public function sayHello() {
    3.                                                                                                                                         ; }
    4. }
    5. trait World {
    6. function
    7. sayWorld() { echo
    8. 'World'
    9. ; { use Hello, World;
    10. }
    11. $o
    12. = new MyHelloWorld();
    13. $o ->sayHello();
    14. $o
    15. ->sayWorld();
    16. ?> Output result:
      Hello World</precourier></span>4) Multi-Traits conflict</span>If two traits added to the same class have the same function name , and if not handled explicitly, an error will be generated. </li>In order to resolve the conflict between two functions with the same name in Tratis in the same class, you need to use the insteadof operator to select the correct function. <li>Because of the uniqueness and exclusivity of methods, the 'as' operator is allowed to be used after conflicting functions to resolve internal conflicts. <span><span></span><span>[php] view plaincopy </span></span><ol start="1"><li><span><span><?php  </span></span></li><li><span>trait A {  </span></li><li><span><span>public</span><span> </span><span>function</span><span> smallTalk() {  </span></span></li><li><span><span>echo</span><span> </span><span>'a'</span><span>;  </span></span></li><li><span>}  </span></li><li><span><span>public</span><span> </span><span>function</span><span> bigTalk() {  </span></span></li><li><span><span>echo</span><span> </span><span>'A'</span><span>;  </span></span></li><li><span>}  </span></li><li><span>}  </span></li><li><span>  </span></li><li><span>trait B {  </span></li><li><span><span>public</span><span> </span><span>function</span><span> smallTalk() {  </span></span></li><li><span><span>echo</span><span> </span><span>'b'</span><span>;  </span></span></li><li><span>}  </span></li><li><span><span>public</span><span> </span><span>function</span><span> bigTalk() {  </span></span></li><li><span><span>echo</span><span> </span><span>'B'</span><span>;  </span></span></li><li><span>}  </span></li><li><span>}  </span></li><li><span>  </span></li><li><span><span>class</span><span> Talker {  </span></span></li><li><span><span>use</span><span> A, B {  </span></span></li><li><span>B::smallTalk insteadof A;  </span></li><li><span>A::bigTalk insteadof B;  </span></li><li><span>}  </span></li><li><span>}  </span></li><li><span>  </span></li><li><span><span>class</span><span> Aliased_Talker {  </span></span></li><li><span><span>use</span><span> A, B {  </span></span></li><li><span>B::smallTalk insteadof A;  </span></li><li><span>A::bigTalk insteadof B;  </span></li><li><span>B::bigTalk <span>as</span><span> talk;  </span></span></li><li><span>}  </span></li><li><span>}  </span></li><li><span>?>  </span></span></li></ol> <phelvetica neue font-size:15px line-height:24px>上面的例子中,Talker使用Traits A 和B,因此两者中相同的函数名称存在冲突。<br>alker中定义了smallTalk取自Traits B,bigTalk取自Traits A。<br>Aliased_Talker中通过使用as操作符来确保Traits B中的bigTalk通过别名talk来实现。<br>5)改变函数访问权限<br>我们可以使用as语法来改变Traits中函数的访问权限属性。<divcourier new width:936.53125px overflow:auto padding-top:1px line-height:26px margin:18px background-color:rgb><p></p> <p>[php] view plaincopy </p> <ol start="1"><li><span><span><?php  </span></span></li><li><span>trait HelloWorld {  </span></li><li><span><span>public</span><span> </span><span>function</span><span> sayHello() {  </span></span></li><li><span><span>echo</span><span> </span><span>'Hello World!'</span><span>;  </span></span></li><li><span>}  </span></li><li><span>}  </span></li><li><span>  </span></li><li><span><span>// Change visibility of sayHello,改变sayHello的访问权限。</span><span>  </span></span></li><li><span><span>class</span><span> MyClass1 {  </span></span></li><li><span><span>use</span><span> HelloWorld { sayHello </span><span>as</span><span> </span><span>protected</span><span>; }  </span></span></li><li><span>}  </span></li><li><span>  </span></li><li><span><span>// Alias method with changed visibility</span><span>  </span></span></li><li><span><span>// sayHello visibility not changed,设置别名myPrivateHello。</span><span>  </span></span></li><li><span><span>class</span><span> MyClass2 {  </span></span></li><li><span><span>use</span><span> HelloWorld { sayHello </span><span>as</span><span> </span><span>private</span><span> myPrivateHello; }  </span></span></li><li><span>}  </span></li><li><span>?>  </span></span></li></ol> <phelvetica neue font-size:15px line-height:24px> <phelvetica neue font-size:15px line-height:24px>6) Traits form new Traits<br>Just like many classes, Traits can be used in classes, and Traits can be used in Traits. One or more Traits can be defined in one Traits, and these Traits can be defined in other Traits as part or all members. <divcourier new width:936.53125px overflow:auto padding-top:1px line-height:26px margin:18px background-color:rgb><p></p> <p>[php] view plaincopy </p> <ol start="1"> <li><span><span><?php </span></span></li><li><span>trait Hello { </span></li><li><span><span>public</span><span> </span><span>function</span><span> sayHello() { </span> </span></li><li><span><span>echo</span><span> </span><span>'Hello '</span> <span>; </span></span></li><li><span>) </span></li>function<li><span> sayWorld() { </span></li><li><span></span></li>echo<li><span> </span></li>'World!'<li><span>; <span></span>use<span></span> Hello, World; <span></span><span></span></span>} </li> <li><span><span> </span><span></span><span></span>class<span></span>MyHelloWorld { </span></li><li><span></span></li>use<li><span>HelloWorld; </span></li><li><span></span>} </li> <li><span></span> </li><li><span><span></span>$o<span></span> = </span></li>new<li><span> MyHelloWorld (); </span></li><li><span></span></li>$o<li><span>->sayHello(); <span></span><span></span></span></span></li>$o<li> <span>->sayWorld(); <span></span><span></span></span> The above routine will output: </li> <li> <span></span>[php] view plaincopy </li> <li><span></span></li> <li>Hello World! <span><span></span><span></span><span>7) Abstract Trait members</span>In order to enforce certain methods in a class, you can use abstract methods in Traits. <span>For example: </span></span> </li> <li>[php] view plaincopy <span><span><ol start="1"> <li><span><span><?php  </span></span></li><li><span>trait Hello {  </span></li><li><span>    <span>public</span><span> </span><span>function</span><span> sayHelloWorld() {  </span></span></li><li><span>        <span>echo</span><span> </span><span>'Hello '</span><span>.</span><span>$this</span><span>->getWorld();  </span></span></li> <li><span>    }  </span></li> <li><span>    <span>abstract</span><span> </span><span>public</span><span> </span><span>function</span><span> getWorld();  </span></span></li> <li><span>}  </span></li> <li><span>  </span></li> <li><span><span>class</span><span> MyHelloWorld {  </span></span></li> <li><span>    <span>private</span><span> </span><span>$world</span><span>;  </span></span></li> <li><span>    <span>use</span><span> Hello;  </span></span></li> <li><span>    <span>public</span><span> </span><span>function</span><span> __construct(</span><span>$world</span><span>) {  </span></span></li> <li><span>        <span>$this</span><span>->world = </span><span>$world</span><span>;  </span></span></li> <li><span>    }  </span></li> <li><span>    <span>public</span><span> </span><span>function</span><span> getWorld() {  </span></span></li> <li><span>        <span>return</span><span> </span><span>$this</span><span>->world;  </span></span></li> <li><span>    }  </span></li> <li><span>}  </span></li> <li><span>  </span></li> <li><span><span>/**</span> </span></li> <li><span><span> * The new function of 5.4 is used here, class instance resolution reference operation </span> </span></li> <li><span><span> * (new class())->method();</span> </span></li> <li><span><span>*/</span><span>  </span></span></li> <li><span>(<span>new</span><span> MyHelloWorld(</span><span>'Arvin'</span><span>))->sayHelloWorld();  </span></span></li> <li><span>?>  </span></li> <li><span>  </span></li> <li><span>该实例输出:  </span></li> <li><span>Hello Arvin  </span></li> </ol> <phelvetica neue font-size:15px line-height:24px> <phelvetica neue font-size:15px line-height:24px>8)静态Trait成员<phelvetica neue font-size:15px line-height:24px>在Traits中不能定义static 静态变量,但是可以定义在Tratis的函数中。Tratis中同样可以定义静态函数。<divcourier new width:936.53125px overflow:auto padding-top:1px line-height:26px margin:18px background-color:rgb><p></p> <p>[php] view plaincopy </p> <ol start="1"> <li><span><span><?php </span></span></li><li><span>trait Counter { </span></li><li><span> <span>public</span><span> </span><span>function</span><span> inc() { </span></span></li><li><span> <span>static</span><span> </span><span>$c</span><span> = 0;</span><span>//静态变量</span><span> </span></span></li><li><span> <span>$c</span><span> &#43;= 1; </span></span></li><li><span> <span>echo</span><span> </span><span>"$c\n"</span><span>; </span></span></li><li><span> } </span></li><li><span> <span>/**</span> </span></li><li><span><span> * 静态方法</span> </span></li><li><span><span> */</span><span> </span></span></li><li><span> <span>public</span><span> </span><span>static</span><span> </span><span>function</span><span> doSomething() { </span></span></li><li><span> <span>echo</span><span> </span><span>'Doing something'</span><span>; </span></span></li><li><span> } </span></li><li><span>} </span></li><li><span> </span></li><li><span><span>class</span><span> C1 { </span></span></li><li><span> <span>use</span><span> Counter; </span></span></li><li><span>} </span></li><li><span> </span></li><li><span>(<span>new</span><span> C1())->inc(); </span><span>// echo 1</span><span>  </span></span></li> <li><span>C1::doSomething();  </span></li> <li><span>?>  </span></li> <li><span>输出为:  </span></li> <li><span>1  </span></li> <li><span>Doing something  </span></li> </ol> <phelvetica neue font-size:15px line-height:24px>9) Traits 定义属性<phelvetica neue font-size:15px line-height:24px>如果在一个trait中定义了一个属性,则在引用该trait的类中不能定义同名的属性,如果该类中定义有和trait中已定义属性具有相同的名字和访问可见性,则是一个<span><codeandale mono sans font-size:13px line-height:normal>E_STRICT</codeandale></span> 提示,否则抛出语法错误。<pre name="code" courier pitch monospace font-size: line-height: margin-bottom: padding: background-color: rgb><?php trait PropertiesTrait { public $x = 1; public $y = 2; } class PropertiesExample { use PropertiesTrait; public $x = 1; //public $y = 3; } $example = new PropertiesExample; echo $example->x, $example->y; ?> 输出: 12
      Copy after login
       在最后贴上php5.4.0部分新功能changelog:
      Added short array syntax support ([1,2,3]), see UPGRADING guide for full details.
      Added binary numbers format (0b001010).
      Added support for Class::{expr}() syntax.
      Added support for Traits.//本文的主要内容
      Added closure $this support back.
      Added array dereferencing support.//数组解引用支持,上文中有实例
      Added callable typehint.
      Added indirect method call through array. #47160.
      Added DTrace support.//传说DTrace是一个性能分析工具,可以跟踪出函数调用点,返回点等数据
      Added class member access on instantiation (e.g. (new foo)->bar()) support.//类新实例解引用操作,上文中有实例
      Copy after login
      本文旨在抛砖引玉,希望大家一起继续探究php5.4的新功能。^_^

      以上就介绍了Traits的用法,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template