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.
-
use A\B as C; $_ = C::class;
resolves to
A\B
, which is perfect 🙂 -
class C { public function f() { $_ = self::class; } }
resolves to
C
, which is perfect 😀 -
class C { } class D extends C { public function f() { $_ = parent::class; } }
resolves to
C
, which is perfect 😄 -
class C { public static function f() { $_ = static::class; } } class D extends C { } D::f();
resolves to
D
, which is perfect 😍 -
'foo'::class
resolves to
'foo'
, which is… huh? 🤨 -
"foo"::class
resolves to
'foo'
, which is… expected somehow 😕 -
$a = 'oo'; "f{$a}"::class
generates a parse error 🙃
-
PHP_VERSION::class
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).
The following looks a bit off:
“`
use A\B as C;
$_ = C::class;
resolves to C, which is perfect 🙂
“`
That would be worrisome, for C is the alias, not the class.
Field testing told me it’s actually A\B, which is perfect 🙂
LikeLike
You’re right! Fixed. Sorry for the typo!
LikeLike
`::class is very useful to get rid off of the get_class`
it is not useful when you need to get the class of an instance of an object.
LikeLike
When the object is `$this`, it can be :-).
LikeLike
For me the best is that calling ::class doesn’t load the class into memory, it simply returns left side of the operand.
LikeLike
as I website owner I think the articles here is real excellent, thanks for your efforts.
LikeLike