关于trait()

2022-10-09

php 5.4.0 起,php 实现了一种代码复用的方法,称为 trait

trait 是为类似 php 的单继承语言而准备的一种代码复用机制。trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method

  • trait看上去更像是为了代码的复用而写的一个小插件,它类似于include 可以用use放在类中间,让trait里面定义的方法作为class的一部分 本身不能直接实例化,trait的作用域在引用该trait类的内部是都可见的(publicprivate 等等都可以) 可以理解为use关键字将trait的实现代码copy了一份到引用该trait的类中 。
<?php trait ezcreflectionreturninfo {
    function getreturntype() { /*1*/ }
    function getreturndescription() { /*2*/ }
}

class ezcreflectionmethod extends reflectionmethod {
    use ezcreflectionreturninfo;
    /* ... */ }

class ezcreflectionfunction extends reflectionfunction {
    use ezcreflectionreturninfo;
    /* ... */ } ?>

优先级

从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。

<?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! ?> 

<?php trait helloworld {
    public function sayhello() {
        echo 'hello world!';
    }
}

class theworldisnotenough {
    use helloworld;
    public function sayhello() {
        echo 'hello universe!';
    }
} $o = new theworldisnotenough(); $o->sayhello();    #输出:hello universe!  ?>

多个 trait

通过逗号分隔,在 use 声明列出多个 trait,可以都插入到一个类中。

<?php trait hello {
    public function sayhello() {
        echo 'hello ';
    }
}

trait world {
    public function sayworld() {
        echo 'world';
    }
}

class myhelloworld {
    use hello, world;
    public function sayexclamationmark() {
        echo '!';
    }
} $o = new myhelloworld(); $o->sayhello(); $o->sayworld(); $o->sayexclamationmark(); ?>

如果两个 trait 都插入了一个同名的方法,如果没有明确解决冲突将会产生一个致命错误。

引用地址:

《关于trait().doc》

下载本文的Word格式文档,以方便收藏与打印。