紫悦博客

不进则退,退一步万丈悬崖!

0%

PHP Trait

自PHP5.4.0是PHP实现代码重用称为性状的方法。

性状是单继承的语言,如PHP的机制,代码重用。性状的目的是通过使开发人员能够在几个独立的类生活在不同的类层次重用套自由的方法来降低单继承的一些限制。性状和类组合的语义方式,也降低了复杂性定义,并避免与多重继承和混入相关的典型问题。

一个特点是相似的一类,但只用于组功能的细粒度和一致的方式。这是不可能实例化一个性状本身。这是一个除了传统的继承,使行为的横构图;也就是说,类成员的应用程序,而不需要继承。

Example #1 Trait example

<?php
trait ezcReflectionReturnInfo {
    function getReturnType() { /*1*/ }
    function getReturnDescription() { /*2*/ }
}

class ezcReflectionMethod extends ReflectionMethod {
    use ezcReflectionReturnInfo;
    /* ... */
}

class ezcReflectionFunction extends ReflectionFunction {
    use ezcReflectionReturnInfo;
    /* ... */
}
?>

**优先权 **
从基类继承的成员是由一个Trait插入成员覆盖。优先顺序是,从当前类重写Trait的方法,它的成员在返回重写继承的方法。

Example #2 Precedence Order Example

<?php
class 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!
本文来自:http://www.php100.com/cover/php/86.html