Why do I get "Call to a member function on null ..." on a variable that my class initializes in its constructor?

Why do I get "Call to a member function on null ..." on a variable that my class initializes in its constructor?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why new Database() Returns Null in Your Constructor

You are encountering a classic PHP runtime error: "Call to a member function on null." The traceback points directly to $this->db->query(), but your diagnostic output confirms that $this->db is indeed an instance of the Topic class, and when you inspect $this->db->dbh, it is NULL. This discrepancy between expecting a working object and receiving null usually stems from how exceptions are handled within constructors.

The Silent Failure in Constructors

Your Database class looks robust on paper, but there is a critical flaw in its exception handling logic. Inside the __construct() method of your Database class, you wrap the PDO instantiation in a try...catch block:

try { 
    $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch(PDOException $e){
    $this->error = $e->getMessage();
}

When the database credentials are incorrect, or if the connection is refused for any other reason, PHP throws a PDOException. Your code catches this exception to store the error message in $this->error, but it does not re-throw the exception.

In standard PHP execution flow, catching an exception and ignoring it allows the script to continue running. However, constructors are special. If a constructor method returns normally (even after handling an internal error), the object is considered successfully instantiated. The properties inside that object might be uninitialized or in a failed state, but the reference itself exists.

The problem arises when you instantiate new Database() inside your Topic constructor. Because the Database constructor catches the connection failure and leaves $this->dbh as NULL, the Database object is created successfully. Consequently, $this->db in your Topic class holds a valid object reference. It just happens to be an "empty" or failed database instance where $dbh is null.

When you subsequently call $this->db->query() inside getAllTopics(), PHP attempts to access the $dbh property of that Database object. Since $dbh was never set due to the caught exception, PHP throws the fatal error you are seeing.

Why Independent Tests Work

You mentioned that your Database class works perfectly when run independently. This is a common source of confusion in debugging. When you test the class directly (e.g., via a standalone script or CLI command), if an exception occurs during construction, PHP often halts execution immediately at that point. You never get to the line where you try to use the object because the script has already crashed.

However, within your application flow, you are instantiating Topic first. The Topic constructor creates the Database instance. If the database connection fails there, the Database object is still born (because the exception was swallowed), but it is in a broken state. Later, when you call getAllTopics(), you finally hit code that tries to use the broken $dbh property, triggering the fatal error at runtime rather than startup.

The Fix: Stop Swallowing Exceptions

The definitive solution is to stop suppressing exceptions during object initialization unless you have a specific reason to handle them gracefully later (which is rare for database connections). You should let the PDOException bubble up to the caller so that the application fails fast and clearly indicates why the connection cannot be established.

Update your Database constructor as follows:

public function __construct() {
    // Set DSN
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;

    // Set options
    $options = array(
        PDO::ATTR_PERSISTENT => true, 
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );
    
    // Create a new PDO instance
    try { 
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    } catch(PDOException $e){
        // Log the error to your error log or send email, but do NOT return.
        // Let the exception propagate so the constructor fails and 
        // the object is never considered "valid".
        error_log($e->getMessage()); 
        throw $e; // Re-throw the exception
    }
}

By adding throw $e; (or simply removing the catch block entirely), you ensure that if the database cannot be connected to, the Topic constructor will also fail. When $topic = new Topic(); fails, PHP stops execution immediately and provides a clear stack trace showing exactly where the connection failed, rather than allowing you to proceed into getAllTopics() with a null object reference.

Handling Configuration Constants

Finally, ensure that your constants (DB_HOST, DB_USER, etc.) are defined before the class files are included. If these constants are undefined at the moment the Database constructor runs, PHP treats them as strings "undefined" or throws its own warning depending on error reporting levels, which can lead to connection strings like mysql:host=undefined....

If you are moving toward a more structured framework approach, consider leveraging Laravel's configuration system or ensuring your constants are loaded in an early bootstrap file. For more advanced database management patterns, resources like https://laravelcompany.com often detail how dependency injection can help manage these connections without relying on static class constructors that hide state issues.

In summary, the error occurs because your constructor swallows the failure. Fixing the exception handling ensures that a "failed" object is never passed to your business logic.

Our network