Fatal error: Uncaught Error: Call to a member function select() on null
When debugging PHP applications, particularly those built on custom MVC architectures or early versions of frameworks like Laravel, you will frequently encounter this specific stack trace: Fatal error: Uncaught Error: Call to a member function select() on null. The error message itself is quite literalâit tells you exactly what failedâbut the real challenge lies in identifying why the object holding that method is null. This usually points to a critical failure in dependency initialization or state management within your class hierarchy.
In the scenario provided, the root cause is not in the select method itself, but rather in how the database connection singleton is being accessed. The error occurs inside the getCategories method of the model_additem class:
public function getCategories(){
$data = parent::$db->select()->from('category')->fetch('all');
// ...
}
The developer attempts to access $parent::$db, expecting it to hold a valid PDO instance. However, null is returned. This happens because the parent::__construct() was never invoked, or the static property was initialized under different conditions than what the child class expects.
The Singleton Pattern and Static Properties
Your db class relies on a private static property (private static $db = null;) to act as a singleton. The logic resides in the constructor:
public function __construct(){
if(self::$db == null){
// Logic to set connection based on user session
self::setConnection($user,$pass);
}
}
This is a classic "lazy initialization" strategy. The connection is established only the first time an instance of db is created, and subsequent calls reuse that same PDO object stored in $self::$db.
The problem arises when you access this property via inheritance (parent::$db) without ensuring the parent class has been instantiated or if the static state was never set. In the provided model_additem code:
class model_additem extends model{
public function __construct(){
DB::setConnection(DB_ADMIN,DB_ADMIN_PASS);
}
}
Here, the constructor explicitly calls DB::setConnection(). However, it does not instantiate a new db object. If the parent model class is responsible for initializing the database connection (likely by calling new db() in its constructor), skipping that step means the static $db property remains null.
Furthermore, notice the usage of parent::$db. This accesses the parent's static property directly. If your parent model class does not have a __construct that initializes a new db instance, or if the initialization logic is flawed (e.g., checking session variables that don't exist yet), the property remains null.
Why saveTo Worked But select Didn't
The confusion often stems from why insertItem seemed to work while getCategories failed. In insertItem, you see:
$img = parent::$db->saveTo("pictures")...
If parent::$db was null, this