TIL PHP ::class keyword

Jump to: TL;DR

According to PHP documentation about the ::class keyword, it can be used for class name resolution:

You can get a string containing the fully qualified name of the ClassName class by using ClassName::class.

1namespace NS {
2    class ClassName {
3    }
4
5    echo ClassName::class;
6}
7
8// outputs: "NS\ClassName"

It’s handy when you need to pass FQCN around. Some people even started using it to make sure that their code was referencing existing classes.

Except that it’s written nowhere in the documentation that this keyword will ensure that the generated FQCN maps to an existing class!

In fact, you can use this keyword on classes that are neither defined nor autoloadable.

 1use Foo\Bar;
 2
 3namespace NS {
 4    echo ClassThatDoesNotExist::class . PHP_EOL;
 5}
 6
 7echo Bar::class;
 8
 9// outputs:
10// "NS\ClassThatDoesNotExist"
11// "Foo\Bar"

Yup, \NS\ClassThatDoesNotExist won’t be autoloaded. It’s FQCN will just be generated using the current namespace or use statements.

TL;DR

The ::class keyword also works on classes that does not exist. It will only generate a FQCN, without actually autoloading the class and checking its existence.