PHP error guide
PHP "Call to a member function on null": Causes and Fixes
Error summary
You called a method on a variable that is null—usually an optional dependency, failed lookup, or missing null check. Guard the value or fix the upstream factory.
What it means
You called a method on a variable that is null—usually an optional dependency, failed lookup, or missing null check. Guard the value or fix the upstream factory.
What the error means
Method call syntax $obj->method() requires an object instance. Null means nothing was assigned or a finder returned null.
Why PHP produces it
PHP 7+ throws an Error for method calls on non-objects instead of a softer failure in many cases.
PHP version notes
Related: “Attempt to read property on null” for property access.
Most common causes
- Finder returned null for missing entity
- Optional service not configured
- Typo assigning wrong variable
- Chained calls without nullsafe operator where appropriate
Minimal examples
BAD — reproduces the problem
$user = $repo->find($id); // null\nreturn $user->getEmail();
FIXED — safer pattern
$user = $repo->find($id);\nreturn $user?->getEmail();
Step-by-step diagnosis
- Identify the variable before
->on the reported line. - Trace its last assignment.
- Determine whether null is allowed by business rules.
Fixes
Fix #1: Explicit null handling
Fail clearly when the object is required.
$user = $repo->find($id);\nif ($user === null) {\n throw new RuntimeException('User not found');\n}\nreturn $user->getEmail();
Fix #2: Nullsafe calls for optional chains
Use ?-> when a null result should propagate.
$email = $order->getCustomer()?->getEmail();
Common mistakes when fixing it
- Using
@$obj->method()to hide the fatal (does not work for Errors the way people expect)
How to prevent it
- Nullable types + static analysis (PHPStan/Psalm)
- Avoid untyped finder return values
Web server / environment notes
All SAPIs
Tags: cli,fpm,laravel,symfony