首页 > 编程 > PHP > 正文

PHP 设计模式 单例模式(Singleton)

2019-11-08 02:56:09
字体:
来源:转载
供稿:网友
<?php class Singleton{ PRivate static $_instance = NULL; private function __construct(){ echo "construct!"; } public static function getInstance(){ if(self::$_instance === NULL){ self::$_instance = new Singleton(); //$_instance=对象 } return self::$_instance; } public function test(){ echo "test!"; } } /*例1:*/ $a=Singleton::getInstance();//实例化类 不能$a = new Singleton();//由于__construct是private类型,所以会报错 $a->test(); //最终输出 "construct!test!" /*例2:*/ $a=Singleton::getInstance(); $a->test(); $b = Singleton::getInstance(); $b->test(); //最终输出 "construct!test!test!"

http://blog.csdn.net/forevernull/article/details/43670195


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表