Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

633
Visualizações
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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

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);
over 4 years ago · Santiago Trujillo Relatório

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda