当前位置:首页 > PHP教程 > php高级应用 > 列表

php单例模式实现方法分析

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-16 13:06:27 浏览: 评论:0 

这篇文章主要介绍了php单例模式,实例分析了单例模式的原理与实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下。

本文实例讲述了php单例模式实现方法,分享给大家供大家参考,具体如下:

  1. <?php 
  2. /** 
  3.  * @copyright 2013 maguowei.com 
  4.  * @author Ma Guowei <imaguowei@gmail.com> 
  5.  */ 
  6. /** 
  7.  * 单例模式 
  8.  * Class Single 
  9.  */ 
  10. class Single 
  11. { 
  12.   private $name; 
  13.   private static $single; 
  14.   private function __construct() 
  15.   { 
  16.   } 
  17.   public static function init() 
  18.   { 
  19.     if(emptyempty(self::$single)) 
  20.     { 
  21.       self::$single = new Single(); 
  22.     } 
  23.     return self::$single; 
  24.   } 
  25.   public function getName() 
  26.   { 
  27.     return $this->name; 
  28.   } 
  29.   public function setName($name) 
  30.   { 
  31.     $this->name = $name; 
  32.   } 
  33. } 
  34. $s = Single::init(); 
  35. $s->setName('hhhh'); 
  36. echo '$s:'.$s->getName(); 
  37. unset($s); 
  38. $m = Single::init(); 
  39. echo '$m:'.$m->getName(); 

希望本文所述对大家的php程序设计有所帮助。

Tags: php单例模式

分享到: