0

I have a class with global $connection but when I try to access it I am getting NULL. As you can see if i try to access within the constructor I do not get NULL. But from getConnection() I am getting 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 
    }

}

Same thing happens when I instantiate an object $connection = new DatabaseManipulation();. Am I doing something wrong? I want this to be done in OO way. Can anyone help me ?

Naveen Niraula
  • 771
  • 10
  • 19

2 Answers2

1

You are using OO PHP not procedural. So change it to:

$this->connection = new mysqli("localhost", "root", "", "db");;
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

I want this to be done in OO way.

Then stop using global. You don't want to refer to a global state when you're in a class. A quick look to The Basics and you will find that a pseudo-variable $this is available inside your object.

class DatabaseManipulation
{
    private $connection;

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

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

More about it:

  1. Why is Global State so Evil?
  2. What does the variable $this mean in PHP?
Community
  • 1
  • 1
Federkun
  • 36,084
  • 8
  • 78
  • 90