[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();
?>