private function __clone(){ } function sayHi(){ return The Class is saying hi to u } } echo Stat::getInstance()- sayHi(); class Stat{ static $instance = NULL; static function getInstance(){ if(self::$instance == NULL){ self::$instance = new Stat(); } return self::$instance; } private function __construct(){ }
private function __clone(){ } function sayHi(){ return The Class is saying hi to u } } echo Stat::getInstance()- sayHi();但,PHP是一種解釋型的語言,在這里用單例好像看不出實際的用處,一旦整個頁面執行完,變量也就消失了。static function getInstance(){ if(self::$instance == NULL){ self::$instance = new Stat(); //這里隨著頁面的重載會再次執行 } return self::$instance; } static function getInstance(){ if(self::$instance == NULL){ self::$instance = new Stat(); //這里隨著頁面的重載會再次執行 } return self::$instance; }我接觸PHP時間不長,以上寫出來的只是在C#與PHP二種不同語言環境下對單例模式的認知,也許這個例子只是為了說明模式可以用很多種語言來實現,但并不意味著在各種語言環境下都能真正起作用。asp.net中的單例是在整個應用程序域唯一。PHP中的單例只在整個頁面周期內唯一html教程