加入收藏 | 设为首页 | 会员中心 | 我要投稿 源码网 (https://www.900php.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php4和php5单态方式 Singleton Pattern 写法

发布时间:2022-03-09 05:00:19 所属栏目:PHP教程 来源:互联网
导读:单态模式(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=nu
  单态模式(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();
  }

(编辑:源码网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读