Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

591
Views
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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
about 4 years ago · Santiago Trujillo Report

0

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().

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!