user3723666
user3723666

Reputation: 231

why is this php variable undefined

Can anyone tell me why this does not work.

class class1 {

    private $database;

    function class1()  
    {  

        $database = $this->connect();


    } 

    private function connect(){

        $database = mysqli_connect("localhost","username","","db");

        if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        return $database;

    }

    private function usedb(){
        $query = "some sql";
        mysqli_query($database,$query);
    }

}

I hope this simple example can portray my problem clearly enough. Anyway, when I run something like this I get an error displayed telling me that there has been a reference to an undefined variable "database" in the "usedb()" function. As if the variable has gone out of scope... Can anyone give me a solution?

Upvotes: 0

Views: 69

Answers (2)

Harutyun Abgaryan
Harutyun Abgaryan

Reputation: 2023

change

$database = $this->connect();

to

$this->database = $this->connect();

and all $database variable change to $this->database for set

Upvotes: 0

Kypros
Kypros

Reputation: 2986

Thats because in class1() you declare another local variable $database through:

    $database = $this->connect();

To set and access the $database property of the class you should use:

    $this->database = $this->connect();

Same goes for the usedb() function:

private function usedb(){
    $query = "some sql";
    mysqli_query($this->database,$query);
}

So your final code should look like this:

class class1 {

     private $database;

     function class1()  
     {  
         $this->database = $this->connect();
     } 

     private function connect()
     {
         $database = mysqli_connect("localhost","username","","db");

         if (mysqli_connect_errno()) 
         {
             echo "Failed to connect to MySQL: " . mysqli_connect_error();
         }
         return $database;
     }

     private function usedb()
     {
         $query = "some sql";
         mysqli_query($this->database,$query);
     }
}

NOTE:

The same applies for the $database variable in connect() function. Although with an identical name, it has nothing to do with the outside $database variable, since that should be access using $this->database (if needed)

Upvotes: 2

Related Questions