2014-10-30 69 views
3

我是一名PHP新手。 這裏是一個非標準Singleton模式例如根據phptherightway.comPHP中的單例模式示例

<?php 
class Singleton 
{ 
    public static function getInstance() 
    { 
     static $instance = null; 
     if (null === $instance) { 
      $instance = new static(); 
     } 

     return $instance; 
    } 

    protected function __construct() 
    { 
    } 

    private function __clone() 
    { 
    } 

    private function __wakeup() 
    { 
    } 
} 

class SingletonChild extends Singleton 
{ 
} 

$obj = Singleton::getInstance(); 
var_dump($obj === Singleton::getInstance());    // bool(true) 

$anotherObj = SingletonChild::getInstance(); 
var_dump($anotherObj === Singleton::getInstance());  // bool(false) 

var_dump($anotherObj === SingletonChild::getInstance()); // bool(true) 

的問題是,在這條線:

 static $instance = null; 
     if (null === $instance) { 
      $instance = new static(); 
     } 

所以,按照我的理解if (null === $instance)始終爲TRUE,因爲每次我打電話的方法getInstance()變量$instance始終設置爲null並且總是會創建一個新實例。 所以這不是一個單身人士。你能解釋我嗎?

+1

以防萬一http://stackoverflow.com/questions/8776788/best-practice-on-php-singleton-classes – 2014-10-30 07:24:03

+1

static $ instance = null;將僅在第一次函數調用時執行 - 在其他函數中將被忽略 – 2014-10-30 07:40:13

回答