ReflectionException
PHPERRORNotableReflection

Reflection API error — class or method not found

Quick Answer

Check class_exists() and method_exists() before using Reflection; use ReflectionException in DI containers to report misconfigured services.

What this means

Thrown by the Reflection API when attempting to reflect a class, method, or property that does not exist.

Why it happens
  1. 1ReflectionClass on a class name with a typo
  2. 2DI container cannot reflect an interface with no implementation

Fix

Guard with class_exists

Guard with class_exists
if (!class_exists($className)) {
    throw new \InvalidArgumentException("Class not found: $className");
}
$ref = new \ReflectionClass($className);

Why this works

class_exists() check avoids the ReflectionException and gives a clearer error message.

Code examples
Triggerphp
new \ReflectionClass('NonExistentClass'); // ReflectionException
Safe reflectphp
try {
    $m = new \ReflectionMethod($obj, $method);
} catch (\ReflectionException $e) {
    throw new \BadMethodCallException("$method not found on " . get_class($obj), 0, $e);
}

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PHP errors