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

PHP Singleton pattern, fatal error when calling getter

我是 PHP 的新手,我尝试以 OOP 方式学习它,因为我已经了解它了。我的问题是我不知道为什么在尝试获取 mysqli 连接时会出现以下空错误。

Fatal error: Uncaught Error: Call to a member function getConn() on null

    <?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 方法中,您创建了 class 实例,您编写了 $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(); 

}
?>