免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2030 | 回复: 3
打印 上一主题 下一主题

这个类用到了php4的单例模式吗?_php4.3.4 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-17 15:08 |只看该作者 |倒序浏览

  1. <?php
  2. class SingletonPhp4{      
  3.    function getInstance(){           
  4.      static $instance=null;           
  5.      if(!$instance){               
  6.          $instance= new SingletonPhp4();           
  7.   }           
  8.      return $instance;      
  9.    }
  10.          
  11.    function SingletonPhp4(){         
  12.    }         
  13. function Show(){           
  14.    echo "Singleton on Php4<br/>OK</br>right";      
  15.    }   
  16. }      
  17.    $Singleton=SingletonPhp4::getInstance();      
  18.    $Singleton->Show();  
  19. ?>
复制代码

getInstance()不是静态的怎么能直接调用呢?

论坛徽章:
0
2 [报告]
发表于 2009-03-17 15:24 |只看该作者
function getInstance(){           
     static $instance=null;           
     if(!$instance){               
         $instance= new SingletonPhp4();           
  }      

在 getInstance()中,static $instance=null,紧接着把这个变量 new成了 SingletonPhp4()的一个对象,下次再调用的时候,已经有 $instance对象了($instance是static的)所以返回的也是这个对象的句柄,从单件模式的概念上来说和 static function getInstance(){} 的功能是一样的,所以是实现了 单件模式的功能

论坛徽章:
0
3 [报告]
发表于 2009-03-17 15:40 |只看该作者


  1. function getInstanceAg(){           
  2.      static $instanceAg=null;           
  3.      if(!$instanceAg){               
  4.          $instanceAg= new SingletonPhp4();           
  5.   }     

复制代码


若是把上面这个方法加进去

那不是就有两件了?


  1. $Singleton=SingletonPhp4::getInstance();
复制代码

对于这句我还不大明白,类还没有实例怎么就能调用非静态的方法了呢?

论坛徽章:
0
4 [报告]
发表于 2009-03-17 16:02 |只看该作者
原帖由 wabomo 于 2009-3-17 15:40 发表


function getInstanceAg(){           
     static $instanceAg=null;           
     if(!$instanceAg){               
         $instanceAg= new SingletonPhp4();           
  }     



若 ...


   刚试了下 php居然也支持这么写....太假了

[ 本帖最后由 hbl.ncut 于 2009-3-17 16:34 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP