请问如下代码中$oa = Single::getinstance();这句就相当于实例化吗?为什么可以直接使用Single::getinstance();就可以访问这个类中的方法?谢谢
class Single{
private $name;
private function __construct(){
}
static public $instance;
static public function getinstance(){
if(!self::$instance) self::$instance = new self();
return self::$instance;
}
public function setname($n){
$this->name = $n;
}
public function getname(){
return $this->name;
}
}
$oa = Single::getinstance();
$ob = Single::getinstance();
$oa->setname('hello world');
$ob->setname('good morning');
echo $oa->getname();
echo '<br/>';
echo $ob->getname();
因为 getInstance方法里通过
new self()
将自身实例化并作为返回值返回。