单例模式PHP实现代码
2018-07-20 来源:open-open
<?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();
?>
标签: 数据库
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇: iOS常用加密算法
最新资讯
热门推荐