-2

我使用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類的構造函數獲取調用僅前行?

它應該被再次調用第二行。

爲什麼它表現得如此怪異?

+0

但是你*在靜態方法':: get_instance()'中構造對象!那麼,你在說什麼?!此外,'static :: $ instance'和'new static()',也可以引用'butto'的任何潛在衍生物(與'self :: $ instance'和'new self()'對比),所以解釋爲什麼他們各自的構造函數也被調用,如果從他們自己的上下文中調用。 –

+0

另請參閱https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5的答案。 – localheinz

回答

1

因爲您的get_instance()本身具有這種邏輯。您正在將實例分配給您的靜態變量。靜態變量在同一類的不同實例之間「共享」。因此,當您第一次調用函數get_instance()時,您正在創建對象並將其存儲在您的靜態變量$instance中。下次當你調用相同的函數時,你的if條件結果是錯誤的,因此不需要創建一個新的對象/實例。再看看下面的代碼:

public static function get_instance() { 
    if(!static::$instance instanceof static) { 
    static::$instance = new static(); 
    } 
    return static::$instance; 
} 

它不是行爲怪異的方式,但它的行爲表現爲你的代碼要求它的行爲。

相關問題