[PHP] php单例模式实现 →→→→→进入此内容的聊天室

来自 , 2021-02-08, 写在 PHP, 查看 170 次.
URL http://www.code666.cn/view/881c6efa
  1. <?php
  2. class SqlHelper
  3. {
  4.     private static $_instance;
  5.     public $_dbname;
  6.     private function __construct()
  7.     {
  8.     }
  9.     //getInstance()方法必须设置为公有的,必须调用此方法
  10.     public static function getInstance()
  11.     {
  12.         //对象方法不能访问普通的对象属性,所以$_instance需要设为静态的
  13.         if (self::$_instance === null) {
  14.             //                self::$_instance=new SqlHelper();//方式一    
  15.             self::$_instance = new self(); //方式二        
  16.         }
  17.         return self::$_instance;
  18.     }
  19.     public function getDbName()
  20.     {
  21.         echo $this->_dbname;
  22.     }
  23.     public function setDbName($dbname)
  24.     {
  25.         $this->_dbname = $dbname;
  26.     }
  27. }
  28. //    $sqlHelper=new SqlHelper();//打印:Fatal error: Call to private SqlHelper::__construct() from invalid context
  29. $A = SqlHelper::getInstance();
  30. $A->setDbName('数据库名');
  31. $A->getDbName();
  32. //    unset($A);//移除引用
  33. $B = SqlHelper::getInstance();
  34. $B->getDbName();
  35. $C = SqlHelper::getInstance();
  36. $C->getDbName();
  37.  
  38. ?>

回复 "php单例模式实现"

这儿你可以回复上面这条便签

captcha