Common causes
- A database or ORM lookup returned null because the record does not exist
- A property such as $this->db was never initialised in the constructor
- WooCommerce or WordPress objects used too early, for example WC()->cart before it loads
- A function returned false on failure, for example DateTime::createFromFormat() or PDO::query()
- A global variable is not available in the current scope
- A service or dependency missing from the container configuration
How to fix it
- Find where the variable is set. Open the file and line in the error, note the variable before ->method(), and trace back to where it gets its value. That is where the object should have been created.
- Check for null before calling. Add if ($user === null) { ... } and handle the missing case, for example return a 404. Use the nullsafe operator $user?->getName() when null is an acceptable result.
- Initialise dependencies. Make sure properties are set in __construct(), for example $this->db = $db;. With typed properties PHP will tell you earlier if one is missing.
- Run code at the right time. In WordPress, move code that uses WC()->cart, global $post or the current user into a hook like init, wp or template_redirect, instead of running it when the plugin file loads.
- Handle functions that return false. Check results from PDO::prepare(), PDO::query() and DateTime::createFromFormat(). Set PDO::ATTR_ERRMODE to ERRMODE_EXCEPTION so failures throw clear errors.
Guard against a missing object
$user = $repo->find($id);
if ($user === null) {
http_response_code(404);
exit('User not found');
}
echo $user->getName();
// or when null is fine
echo $order?->getCustomer()?->getEmail() ?? 'guest'; How to stop it happening again
- Use nullable return types (?User) so null cases are visible
- Inject dependencies through the constructor
- Hook WordPress code to the right action instead of running it at load
- Run PHPStan or Psalm to catch possible null method calls