Php 为什么我在尝试启动连接时会变为NULL?

Php 为什么我在尝试启动连接时会变为NULL?,php,Php,我有一个全局$connection的类,但是当我尝试访问它时,我得到了NULL。正如您所看到的,如果我尝试在构造函数中访问,我不会得到NULL。但是从getConnection()我得到了空值 class DatabaseManipulation { private $connection; function __construct() { global $connection; $connection = new mysqli("loc

我有一个全局
$connection
的类,但是当我尝试访问它时,我得到了NULL。正如您所看到的,如果我尝试在构造函数中访问,我不会得到NULL。但是从
getConnection()
我得到了空值

class DatabaseManipulation
{
    private $connection;

    function __construct()
    {
        global $connection;
        $connection = new mysqli("localhost", "root", "", "db");
        $result = $connection->query("select * from user");

        print_r($result); //I get an array
    }

    function getConnection(){
        global $connection;
        var_dump($connection); // I get -> object(DatabaseManipulation)#1 (1) { ["connection":"DatabaseManipulation":private]=> NULL } NULL 
    }

}

当我实例化一个对象
$connection=newdatabasemanipulation()时也会发生同样的事情。我做错什么了吗?我希望这是以面向对象的方式完成的。有人能帮我吗?

您使用的是OO PHP,而不是程序化的。因此,将其更改为:

$this->connection = new mysqli("localhost", "root", "", "db");;

您使用的是OO-PHP,而不是过程性的。因此,将其更改为:

$this->connection = new mysqli("localhost", "root", "", "db");;
我希望这是以面向对象的方式完成的

然后停止使用
global
。在类中时,您不希望引用全局状态。快速查看,您会发现对象中有一个伪变量
$this

class DatabaseManipulation
{
    private $connection;

    function __construct()
    {
        $this->connection = new mysqli("localhost", "root", "", "db");
    }

    function getConnection(){
        var_dump($this->connection);
    }
}
更多信息:

  • 我希望这是以面向对象的方式完成的

    然后停止使用
    global
    。在类中时,您不希望引用全局状态。快速查看,您会发现对象中有一个伪变量
    $this

    class DatabaseManipulation
    {
        private $connection;
    
        function __construct()
        {
            $this->connection = new mysqli("localhost", "root", "", "db");
        }
    
        function getConnection(){
            var_dump($this->connection);
        }
    }
    
    更多信息:


  • 我仍然得到错误:注意:未定义变量:连接在…你的代码在哪里?您应该使用
    $this
    $this->connection->query(“select*from user”)你读过上面的代码了吗?此外,请阅读并相应地更改代码。请注意,
    $this->$connection
    !==<代码>$this->connection
    我仍然收到错误:注意:未定义的变量:connection in….您的代码在哪里?您应该使用
    $this
    $this->connection->query(“select*from user”)你读过上面的代码了吗?此外,请阅读并相应地更改代码。请注意,
    $this->$connection
    !==<代码>$this->连接