Random thoughts about ::class
in PHP
The special
::class
constant allows for fully qualified class name resolution at compile, this is useful for namespaced classes.
I'm quoting the PHP manual. But things can be funny sometimes. Let's go through some examples.
resolves to
A\B
, which is perfect πresolves to
C
, which is perfect πresolves to
C
, which is perfect πresolves to
D
, which is perfect πresolves to
'foo'
, which isβ¦ huh? π€¨resolves to
'foo'
, which isβ¦ expected somehow πgenerates a parse error π
resolves to
'PHP_VERSION'
, which isβ¦ strange: It resolves to the fully qualified name of the constant, not the class π€
::class
is very useful to get rid off of the get_class
or the
get_called_class
functions, or even the get_class($this)
trick. This
is something truly useful in PHP where entities are referenced as
strings, not as symbols. ::class
on constants makes sense, but the
name is no longer relevant. And finally, ::class
on single quote
strings is absolutely useless; on double quotes strings it is a source
of error because the value can be dynamic (and remember, ::class
is
resolved at compile time, not at run time).