PromptHub
PHP Beginner 17 views

Call to a Member Function on Null

The code calls a method on a variable that is null instead of an object.

Explanation

This error occurs when you try to call a method on a variable that is null. For example, calling \$user->getName() when \$user is null will trigger this error. This is one of the most common PHP errors, especially in Laravel applications where Eloquent methods may return null. It can also happen when dependency injection fails, when a factory or builder returns null, or when accessing properties that don't exist on an object.

Common Causes

  • Object is null from failed lookup
  • Database query returning no results
  • Dependency injection failure
  • Incorrect method chaining
  • Variable scope issue

Solution

Always check if the object is null before calling methods on it. Use the null safe operator (?->) introduced in PHP 8.0. Use optional() helper in Laravel. Add null checks in your code before method calls. Use type hints with nullable types (?) to make null returns explicit. Consider using the ?? operator for method chaining with defaults. Enable strict_types and use proper return type declarations to prevent null returns.

Code Example

// $user is null, calling method on it causes error
$user = User::find(999); // returns null
$name = $user->getName(); // Error: call to member function on null

// Fix: check for null
$user = User::find(999);
if ($user) {
    $name = $user->getName();
}

// PHP 8.0+ null safe operator
$name = $user?->getName();

// Laravel optional helper
$name = optional($user)->getName();

// Using null coalescing for default
$name = $user->getName() ?? 'Guest';

// Type hint to prevent null returns
public function findUser(int $id): User
{
    return User::findOrFail($id); // throws if null
}

Error Information

Language

php

Difficulty

Beginner

Views

17

Related Errors