基于php设计模式中单例模式的应用分析 |
本文标签:php,设计模式,单例模式 单例模式:简单的说,一个对象只负责一个特定的任务 。 单例类: 复制代码 代码如下: <?php class DanLi{ //静态成员变量 private static $_instance; //私有的构造方法 private function __construct(){ } //防止对象被克隆 public function __clone(){ trigger_error(Clone is not allow!,E_USER_ERROR); } public static function getInstance(){ if(!(self::$_instance instanceof self)){ self::$_instance = new self; } return self::$_instance; } public function test(){ echo "ok"; } } //错误:$danli = new DanLi(); $danli_clone = clone $danli; //正确:$danli = DanLi::getInstance(); $danli->test(); ?> |