static::$instance = $container; } //这样做,启动单例的作用 public static function getInstance() { return static::$instance; } } class A1 extends B1 { public function __construct() { //$this->setInstance($this); static::setInstance($this); } public function hello() { echo "A1 hello Method" . PHP_EOL; } } class A2 extends B1 { public function world() { echo 'A2 world Method' . PHP_EOL; } } $a1Obj = new A1(); B1::getInstance()->hello(); //输出 A1 hello Method A2::getInstance()->hello();
<?php class A1 { public static function getInstance() { return new self(); } } class B1 extends A1 { } $obj = B1::getInstance(); var_dump($obj); //object(A1)#1 (0) { } class A { public static function getInstance() { return new static(); } } class B extends A { } $obj = B::getInstance(); var_dump($obj); //object(B)#2 (0) { }