Random thoughts about ::class in PHP
The special
::classconstant 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.
<?php use A\B as C; $_ = C::class; ``` <!-- rumdl-disable-line MD031 --> resolves to `A\B`, which is perfect ๐<?php class C { public function f() { $_ = self::class; } }resolves to
C, which is perfect ๐<?php class C {} class D extends C { public function f() { $_ = parent::class; } } ``` <!-- rumdl-disable-line MD031 --> resolves to `C`, which is perfect ๐<?php class C { public static function f() { $_ = static::class; } } class D extends C {} D::f();resolves to
D, which is perfect ๐<?php 'foo'::class ``` <!-- rumdl-disable-line MD031 --> resolves to `'foo'`, which isโฆ huh? ๐คจ<?php "foo"::classresolves to
'foo', which isโฆ expected somehow ๐<?php $a = 'oo'; "f{$a}"::class ``` <!-- rumdl-disable-line MD031 --> generates a parse error ๐<?php PHP_VERSION::classresolves 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 of 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).