phpclassrequire-once

Undefined class variable in PHP


I have made a separate class to connect to my database and that class is in a separate PHP file:

connect.php

class connect{

    function __construct(){
        // Connect to database
    }

    function query($q){
        // Executing query
    }
}
$connect = new connect();

Now, I made the object of the class $connect and when use it in a file like index.php it works:

index.php

require_once('connect.php');
$set = $connect->query("SELECT * FROM set");

Now, here it works fine, I don't have to recreate an object for the class and directly execute the query whereas in another file called header.php I have a class like this:

header.php

class header{

    function __construct(){
        require_once('connect.php');
        // Here the problem arises. I have to redeclare the object of the connection class
        // Without that, it throws an error: "undefined variable connect"
        $res = $connect->query("SELECT * FROM table");
    }

}

Why is it working in index.php and not in header.php?


Solution

  • Your problem was probably in using require_once() instead of require(). When you included connect.php for the first time it worked well because variable(s) were initialized and class loaded, but when you tried later again require_once() prohibited repeated inclusion and therefore no variable was initialized.

    Anyway, using include() inside constructor is... rarely justified. And including a file which will initialize local variables is bad idea too.

    The proper code would look like:

    <?php
        require_once('connect.php');
        require_once('header.php');
    
        $connect = new Connect();
        $header = new Header($connect);
    

    And header.php:

    <?php
        class Header{
    
            protected $connection = null;
    
            function __construct(Connect $connection){
                $this->connection = $connection;
                $res = $this->connection->query("SELECT * FROM table");
            }
    
        }