Sometimes you need to write PHP code that includes a check that the class you want to use exists. Because you need to provide the fully qualified class name (the namespace and the classname) our code can end up looking a little messy – but there is a better way.
Example Code That Does Not Work
use salcode\AddOnNotifier;
// This returns false.
if (class_exists('AddOnNotifier')) {
AddOnNotifier::notify();
}
Example Code That Does Work
use salcode\AddOnNotifier;
if (class_exists('salcode\AddOnNotifier')) {
AddOnNotifier::notify();
}
By using the fully qualified class name (i.e. the namespace and the classname, e.g. class_exists('salcode\AddOnNotifier')) PHP is able to properly check the class has been defined, however this would require us to update two places in our code if we ever change the namespace.
The whole point of the use statement is so our code doesn’t need to deal in fully qualified names.
Solution ::class
The ::class keyword provides the fully qualified name of the class (e.g. AddOnNotifier::class provides salcode\AddOnNotifier), so we can use this instead.
Example Code That Does Work Without the Fully Qualified Name
use salcode\AddOnNotifier;
// This always returns false.
if (class_exists(AddOnNotifier::class)) {
AddOnNotifier::notify();
}
Leave a Reply