Harry
Harry

Reputation: 2536

Why doesn't PHP throw class not found error when using ::class?

When using the SomeClass::class syntax to get the FQN of the class, if the class doesn't exist it will just output SomeClass instead of throwing a fatal error.

echo SomeClass::class; // SomeClass

$class = new SomeClass(); // Fatal Error: Uncaught Error: Class 'SomeClass' not found

$const = SomeClass::SOME_CONST; // Fatal Error: Uncaught Error: Class 'SomeClass' not found

This seems undesirable to me. Why does this occur and is there a way to change this behaviour?

Upvotes: 3

Views: 478

Answers (2)

Philipp
Philipp

Reputation: 15629

The ::class-keyword is evaluated at compile time

From the manual

The class name resolution using ::class is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case.

That means, using ::class doesn't call the autoloader and never throws an error. To call the autoloader, you have to create an instance of the class or use any function, which invokes the autoloader (i.e. class_exists)

You could come arround this by defining a simple test function, but I'm not sure, if that's a big benefit at all.

function class_or_fail($name) {
    if (class_exists($name)) {
        return $name;
    }
    throw new \Exception("Invalid class $name");
}

echo class_or_fail(SomeClass::class);

Upvotes: 3

Alex Howansky
Alex Howansky

Reputation: 53581

The class doesn't actually need to be defined in order to determine its FQN. It's simply a matter of using the namespace you're in, or matching any use statement in effect. If you want to determine if the class actually exists, there's a function for that -- class_exists().

Upvotes: 0

Related Questions