其他问题 - Trait与单例
优质
小牛编辑
136浏览
2023-12-01
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(10) "B was call"
string(10) "D was call"
string(9) "call at B"
string(9) "call at D"
string(9) "call at B"