2011-04-28 54 views
0

我創建一個PHP單例類:與Singleton類的實例處理

<?php 
class DataManager 
{ 
    private static $dm; 

    // The singleton method 
    public static function singleton() 
    { 
     if (!isset(self::$dm)) { 
      $c = __CLASS__; 
      self::$dm = new $c; 
     } 

     return self::$dm; 
    } 

    // Prevent users to clone the instance 
    public function __clone() 
    { 
     trigger_error('Clone is not allowed.', E_USER_ERROR); 
    } 
    public function test(){ 
     print('testsingle'); 
     echo 'testsingle2'; 
    } 

    function __get($prop) { 
     return $this->$prop; 
    } 

    function __set($prop, $val) { 
     $this->$prop = $val; 
    } 
} 
?> 

現在,當我嘗試在我的index.php使用這個類:

<?php 
include('Account/DataManager.php'); 

echo 'test'; 
$dm = DataManager::singleton(); 
$dm->test(); 

echo 'testend'; 
?> 

唯一的回聲我得到的,是'test',單例類中的函數test()從來沒有被調用過。此外,index.php末尾的「testend」從未被調用過。

在我的單身課程中是否有錯誤?

+1

無法重現此...示例代碼是在我的機器上工作。 – 2011-04-28 15:52:01

+1

如果您只能進行'echo'測試「;'您可能需要打開錯誤報告。 – 2011-04-28 15:56:16

+0

我認爲處理單身人士課程的最好方法是不要處理他們。 ;) – netcoder 2011-04-28 16:39:25

回答

1

該代碼看起來不錯,雖然我沒有測試過它。但我建議你創建一個私有的或受保護的(但不是公共的)構造函數,因爲你只希望能夠從你的類中創建一個實例(在DataManager::singleton()

+0

奇怪的是,我用MAMP for macosx。顯然MAMP不能按我想要的方式工作。我現在在一臺Windows機器上測試了它,安裝了Xampp,並且確實工作正常。我正在考慮不使用singleton ..感謝arjan,謝謝netcoder和gordon! – Oritm 2011-04-28 22:33:17