php 设计模式之单类模式

直接上代码吧!php

 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 的方法的话会报错spa

 

相关文章
相关标签/搜索