直接上代码吧!
1 <?php 2 class Singleton 3 { 4 private static $_instance = null; 5 6 private function __construct() 7 { 8 } 9 10 public static function getInstance() 11 { 12 if (self::$_instance === null) { 13 self::$_instance = new self(); 14 } 15 16 return self::$_instance; 17 } 18 } 19 20 $obj1 = Singleton::getInstance(); 21 $obj2 = Singleton::getInstance(); 22 var_dump($obj1); 23 var_dump($obj2); 24 ?>
#1是类id,当打印$obj1 和 $obj2 的id是一样就表示只实例化了一个对象
自己在测试单类模式的时候,如果不是通过Singleton::getInstance()的方法而是用new 的方法的话会报错