当前位置: 首页 > 图文教程 > 网络编程 > PHP > php4和php5单态模式(Singleton Pattern)写法

PHP
使用 php4 加速 web 传输
MYSQL中如何存取二进制文件
“在phpMyAdmin使用用户口令登陆”补充
几种显示数据的方法的比较
使用PHP制作新闻系统的思路
关于PHP中操作MySQL数据库的一些要注意的问题
不使用OCI8接口如何连接PHP和Oracle
php 之 没有mysql支持时的替代方案
用session代替apache服务器验证
php实现ping
PHP语句中or的用法
在Linux下安装PHP,APACHE,ORACLE,PERL的方法
一个非常精彩的日历程序
利用static实现表格的颜色隔行显示
php写的域名查询系统whois
用PHP制作的意见反馈表
针对初学PHP者的疑难问答
从C/C++迁移到PHP——判断字符类型的函数
几点提高php序运行效率的方法
Output Buffer (输出缓冲)函数的妙用

PHP 中的 php4和php5单态模式(Singleton Pattern)写法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 162 ::
收藏到网摘: n/a

单态模式(Singleton Pattern) 就是一个类Class只有一个实例存在。(Ensure a class only has one instance, and provide a global point of access to it.)
这个是php5的写法。

以下为引用的内容:
<?php
class SingletonPhp5{
 static private $_instance=null;

 function getInstance(){
  if(! self::$_instance){
   self::$_instance=new self;
  }
  return self::$_instance;
 }

 function __construct(){

 }

 function Show(){
  echo 'Singleton on Php5';
 }
}

{
 $Singleton=SingletonPhp5::getInstance()->Show();
}

这个是php4的写法,当然此方法在php5下也可以正常运行。

以下为引用的内容:

class SingletonPhp4{      
   function &getInstance(){          
     static $_instance=array();          
     if(empty($_instance)){              
         $_instance[]= & new SingletonPhp4();  
        
}          
  return $_instance[0];      

  }
        
function SingletonPhp4(){        

}        

function Show(){          
   echo 'Singleton on Php4';      
   }  
}    

{      
   $Singleton=SingletonPhp4::getInstance();      
   $Singleton->Show();  
}