php5.4 新特性 trait

php5.4中的trails,是新引入的特性。目的是为了有得场合理的让代码实现重用。

注意:trails不是类,不能实例化。如果trails的方法名和类中的方法名冲突,类中的方法名会覆盖trails的方法名。说明类中的方法名,优先级更高。

<?php
trait myTrait {
    function method1() {
        echo "Method 1" . PHP_EOL;
    }

    function method2() {
        echo "Method 2" . PHP_EOL;
    }
}

class Test {
    use myTrait;

    public function method1() {
        echo "Self method 1" . PHP_EOL;
    }
}

$test = new Test();
$test->method1();
$test->method2();

输出结果:

Self method 1
Method 2

 

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>