trait

在学习PHP时遇到trait,不解,研究了一下

官方文档写的很详细
http://www.php.net/manual/zh/language.oop5.traits.php


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

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

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



用trait定义后,使用use 就可以使用里面的函数了


<?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
优先级:当前类会覆盖trait,trait覆盖基类

我在做这个例子的时候在想为什么会输出Hello World,按照优先级应该是输出World,发现parent::sayHello();,parent;;可用于调用父类中定义的成员方法,如果把extends Base去掉,会报错


Fatal error: Uncaught Error: Cannot access parent:: when current class scope has no parent in H:\httpd-2.4.23-win64-VC14\Apache24\htdocs\helloworld.php:10 Stack trace: #0 H:\httpd-2.4.23-win64-VC14\Apache24\htdocs\helloworld.php(20): MyHelloWorld->sayHello() #1 {main} thrown in H:\httpd-2.4.23-win64-VC14\Apache24\htdocs\helloworld.php on line 10

猜你喜欢

转载自201609032307.iteye.com/blog/2343310