• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (deprecated)
You are here: Home / Dev Tips / PHP class_exists() check without the Fully Qualified Class Name

PHP class_exists() check without the Fully Qualified Class Name

Last updated on June 28, 2024 by Sal Ferrarello

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();
}
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP and JavaScript developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a principal engineer.

Filed Under: Dev Tips, Programming, Solution Tagged With: PHP

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2026 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in