Trait与单例


trait A{
    private static $instance;
    static function getInstance()
    {
        if(!isset(self::$instance)){
            self::$instance = new static();
        }
        return self::$instance;
    }
}

class B{
    use A;
    function a()
    {
        var_dump('call at B');
    }
}

class C extends B{
    function a()
    {
        var_dump('call at c');
        parent::a(); // TODO: Change the autogenerated stub
    }
}

class D extends B{
    use A;
    function a()
    {
        var_dump('call at D');
        parent::a(); // TODO: Change the autogenerated stub
    }
}
$b = B::getInstance();
$c = C::getInstance();
$d = D::getInstance();

$c->a();
$d->a();

以上输出:

string(9) "call at B"
string(9) "call at D"
string(9) "call at B"

results matching ""

    No results matching ""