标签:
<?php /** * 单例模式 * * 以前写单例构造器的时候总是为如何把需要的参数传给类而烦恼 * * 如果项目中的类文件都采用这种设计的话就ok了 * * 每次获取实例的时候都可以更新资源变量 */ class Utils_Common { private static $_instances = array(); /** * 单例包装 * @param 类名 $klass * @param 资源变量 $resource * @return null object */ public static function getInstance($klass, $resource = null) { if (isset(self::$_instances[$klass])) { if (null !== $resource) { self::$_instances[$klass]->setResource($resource); } return self::$_instances[$klass]; } else { if (class_exists($klass)) { self::$_instances[$klass] = new $klass($resource); return self::$_instances[$klass]; } else { return null; } } } } class Db { //参数等资源 private $resource; public function __construct($resource) { $this->resource = $resource; } public function setResource($resource) { $this->resource = $resource; } public function getResource() { return $this->resource; } protected function getRsrcParams($key) { return isset($this->resource[$key]) ? $this->resource[$key] : array(); } protected function setRsrcParams($key, $value) { $this->resource[$key] = $value; } public function go() { echo ‘success:‘ . $this->getRsrcParams(‘host‘); } } header(‘Content-Type:text/plain;charset=utf-8‘); Utils_Common::getInstance(‘Db‘, array(‘host‘ => ‘localhost‘))->go();
标签:
原文地址:http://www.cnblogs.com/bai-jimmy/p/4307666.html