当我尝试启动连接时为什么会出现NULL?

时间:2016-12-19 10:46:56

标签: php

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

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 = new DatabaseManipulation();时,会发生同样的事情。难道我做错了什么?我希望这可以用OO方式完成。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

您正在使用OO PHP而不是程序性的。所以改成它:

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

答案 1 :(得分:1)

  

我希望以OO方式完成此操作。

然后停止使用global。当你上课时,你不想引用全球状态。快速查看The Basics,您会发现对象中有伪变量$this

class DatabaseManipulation
{
    private $connection;

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

    function getConnection(){
        var_dump($this->connection);
    }
}

更多信息:

  1. Why is Global State so Evil?
  2. What does the variable $this mean in PHP?
相关问题