Home > Backend Development > PHP Tutorial > 还是说php实现singleton模式

还是说php实现singleton模式

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 14:27:26
Original
1031 people have browsed it

这天考虑用php来singleton一下,看到一篇比较全面的总结 -- singleton模式的几种实现.其中总结的php5的实现:

PLAIN TEXTPHP:

class MyClass
  {
   PRivate static $instance;
 
    public static function singleton()
   {
     if (!isset(self::$instance)) {
       $c = __CLASS__;
       self::$instance = new $c;
      }
     return self::$instance;
 
   }
  }

这段代码拿来使用,不会太爽,因为一般都会继承自MyClass,而$c = __CLASS__;获取的始终是基类的类名,不可用。只能考虑找其它实现方法。


接着俺开始查看文章中的函数方式实现的singleton,实现的很不错,缺点是类被实例化时不能带参数,这里贴上俺的版本:

PLAIN TEXTPHP:

function getObj() {
   static $obj = array();
   $args = func_get_args();
 
   if(empty($args))
     return null;
 
   $clazz = $args[0];
   if(!is_object($obj[$clazz])) {
     $cnt = count($args);
     if($cnt> 1) {
       for($i = 1, $s = ''; $i          $s[] = '$args[' . $i . ']';
       eval('$obj[$clazz] = new $clazz(' . join(',', $s) . ');');
     } else {
       $obj[$clazz] = new $clazz;
     }
   }
 
   return $obj[$clazz];
}

在php5下可以很爽的调用:

PLAIN TEXTPHP:

getObj('MyClass', $param1, $param2)->myMethod();

以前的幼稚版:
单子模式(SINGLETON)的简单实现

http://www.ooso.net/index.php/archives/182

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template