单例模式PHP实现代码

2015-01-20 0 149
单例模式PHP实现代码
<?php
class SqlHelper
{
    private static $_instance;
    public $_dbname;
    private function __construct()
    {
    }
    //getInstance()方法必须设置为公有的,必须调用此方法
    public static function getInstance()
    {
        //对象方法不能访问普通的对象属性,所以$_instance需要设为静态的
        if (self::$_instance === null) {
            //                self::$_instance=new SqlHelper();//方式一   
            self::$_instance = new self(); //方式二       
        }
        return self::$_instance;
    }
    public function getDbName()
    {
        echo $this->_dbname;
    }
    public function setDbName($dbname)
    {
        $this->_dbname = $dbname;
    }
}
//    $sqlHelper=new SqlHelper();//打印:Fatal error: Call to private SqlHelper::__construct() from invalid context
$A = SqlHelper::getInstance();
$A->setDbName('数据库名');
$A->getDbName();
//    unset($A);//移除引用
$B = SqlHelper::getInstance();
$B->getDbName();
$C = SqlHelper::getInstance();
$C->getDbName();
 
?>

遇见资源网 php 单例模式PHP实现代码 http://www.ox520.com/7271.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务