PHP 单例模式,调用 getter 时出现致命错误



我对PHP很陌生,并尝试以OOP的方式学习它,因为我对它有所了解。我的问题是我不知道为什么当我尝试获取 mysqli 连接时会出现下面的空错误。

致命错误:

未捕获错误:调用成员函数 getConn(( on 零

<?php
class ConnectDB
{
private $conn;

private function __construct()
{
$this->conn = new mysqli('localhost', 'root', 'root', 'gs');
$this->checkConnection();
}
public function getConn()
{
return $this->conn;
}
/**
* @return ConnectDB
*/
public static function getInstance()
{
static $instance = null;
if($instance == null)
{
$instance == new ConnectDB();
}
return $instance;
}
public function checkConnection()
{
if($this->conn->connect_errno)
{
echo "Can't connect to Database: " .mysqli_connect_error();
exit();
}
else
{
echo "Connected!";
}
}
}
$conn = ConnectDB::getInstance()->getConn();

getInstance方法中,您在其中创建您编写的类实例$instance == new ConnectDB();.对分配使用单个=

我不认为你的getInstance方法根本不是单例。你在每次调用null时都会初始化变量$instance,所以你每次都应该得到一个新实例。

像这样尝试:

class ConnectDB
{
private $conn;
private static $instance = null;
...
public static function getInstance()
{
if(self::$instance == null)
{
self::$instance == new ConnectDB();
}
return self::$instance;
}
...

看看你是否能做到这一点:

<?php
class ConnectDB {
private $_connection;
private static $_instance; //The single instance
private $_host = "localhost";
private $_username = "root";
private $_password = "root";
private $_database = "gs";
// 
public static function getInstance() {
if(!self::$_instance) { // If no instance then make one
self::$_instance = new self();
}
return self::$_instance;
}
// Constructor
private function __construct() {
$this->_connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()) {
trigger_error(
"Failed to conencto to MySQL: " . mysql_connect_error(),E_USER_ERROR
);
} else{
echo "Connected!";
}
}

private function __clone() { }

public function getConn() {
return $this->_connection;
}
$db = ConnectDB::getInstance();
$mysqli = $db->getConn(); 
}
?>

相关内容

  • 没有找到相关文章

最新更新