我使用PHP 7.1.11構造函數如何在沒有創建對象的情況下調用?爲什麼構造函數沒有以相同的方式再次調用?
考慮下面的工作代碼和它的輸出:
<?php
class butto {
public static $instance;
private function __construct() {
echo 'Contruct of butto class called</br>';
}
public static function get_instance() {
if(!static::$instance instanceof static) {
static::$instance = new static();
}
return static::$instance;
}
public function test() {
echo 'test function called</br>';
}
}
class B extends butto {
public static $instance;
protected function __construct() {
echo 'Construct of Class B called</br>';
}
public static function get_class_name() {
return __CLASS__;
}
}
butto::get_instance()->test();
B::get_instance()->test();
B::get_instance()->test();
/*Output : Contruct of butto class called
test function called
Construct of Class B called
test function called
test function called*/
?>
如果你看一下代碼觀察,你會知道,無論是類的構造函數即使沒有創建任何類的對象也會被調用。
即使我靜態訪問任何靜態方法,構造函數也會被調用。到目前爲止,我知道構造函數只能在創建對象時調用,因爲構造函數的目的是將初始值設置爲對象屬性,並在創建對象時立即使用。
那麼這怎麼可能?以這種方式使用構造函數有什麼好處,即訪問時不需要創建對象?
考慮下面的代碼行:
B::get_instance()->test();
B::get_instance()->test();
我的問題是,爲什麼B類的構造函數獲取調用僅前行?
它應該被再次調用第二行。
爲什麼它表現得如此怪異?
但是你*在靜態方法':: get_instance()'中構造對象!那麼,你在說什麼?!此外,'static :: $ instance'和'new static()',也可以引用'butto'的任何潛在衍生物(與'self :: $ instance'和'new self()'對比),所以解釋爲什麼他們各自的構造函數也被調用,如果從他們自己的上下文中調用。 –
另請參閱https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5的答案。 – localheinz