PHP

Call to a member function on null (PHP)

You called a method on a variable that was null — the object you expected wasn't created.

What it looks like

PHP Fatal error:  Uncaught Error: Call to a member function getName() on null in /var/www/app/profile.php:20

What does "Call to a member function on null (PHP)" mean?

A fatal error raised when code calls a method on a variable that is null. It usually means a lookup found nothing — a database or ORM query returned no row — and the code carried on as if it had.

What causes "Call to a member function on null (PHP)"?

  • A find/query returned null and you used it anyway.
  • A dependency wasn't injected/initialized.
  • An optional value was missing.

How do I confirm the cause?

  1. Find where the variable is assigned (often a find(), first() or getById() call) and log what it returned.
  2. Check the id or key used in that lookup — it may be empty, wrong, or for a record that was deleted.
  3. If the object should be injected (a service or dependency), check the container or constructor actually provides it.

How do I fix "Call to a member function on null (PHP)"?

  • Check for null before calling the method.
  • Log the variable to see why it's null.
  • Ensure the object is created/returned before use.

How do I stop it happening again?

  • Handle “not found” explicitly: return a 404 or a clear message instead of using the result blindly.
  • Use the nullsafe operator ($user?->getName()) where a missing object is expected and acceptable.
Got a different error? Paste it into the Explain This Error tool → Identifies the family and the fix — runs locally, nothing uploaded.

Related errors