<?php /** * 單例模式實現 */ class Singleton { //靜態變量保存全局實例 private static $instance = null; private function __clone() { //私有構造函數,防止外界實例化對象 } private function __construct() { //私有克隆函數,防止外界克隆對象 } //靜態方法,單例統一訪問入口 public static function getInstance() { if (self::$instance instanceof Singleton) { echo "return exist instance\n"; return self::$instance; } self::$instance = new Singleton(); echo "return new instance\n"; return self::$instance; } } $a = Singleton::getInstance();//output: return new instance $a = Singleton::getInstance();//output: return exist instance