class_exists

Checks whether a class is defined, optionally triggering the autoloader to load it.

Signature
class_exists(string $class, bool $autoload = true): bool
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$classstringThe class name, matched case-insensitively. Namespaced names must be fully qualified and written without a leading backslash.
$autoloadoptionalbool= trueWhether to call the registered autoloaders if the class is not already loaded.

Return value

boolReturns true if class is a defined class, false otherwise.

Errors

Throws a TypeError if class is not a string. It does not throw when the class is simply missing — it returns false.

class_exists() answers one question: is this class name usable right now? By default it will ask the registered autoloaders to try to load the class first, so a true result means the class is genuinely available, not merely that a file exists somewhere.

When to reach for it

Use it for optional dependencies — enabling a Redis cache driver only when the extension's class is present, or picking between two PDF libraries. It is also the standard guard before new $className when the name came from configuration or user input, since instantiating a missing class is a fatal Error.

Things that trip people up

  • Interfaces and traits are not classes here. Use interface_exists() and trait_exists() for those. Enums, however, are classes, so class_exists() returns true for them — use enum_exists() if you specifically need an enum.
  • Namespaced names must be fully qualified strings: class_exists('App\\Models\\User'), never 'User' just because a use statement is in scope. Prefer class_exists(User::class), which the compiler expands for you.
  • Passing false for the second argument skips autoloading. That is a load-order check, not an existence check, and is usually not what you want.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Enable an optional feature only when a third-party library's class is installed
  • Validate a class name that came from a config file before calling new $name
  • Register a service in a container only if its driver class can be autoloaded

Frequently asked questions

Does class_exists trigger the autoloader?

Yes, by default. Pass false as the second argument to check only classes that are already loaded, though that is rarely what you want in application code.

Why does class_exists return false for my interface?

Because interfaces are not classes as far as this function is concerned. Use interface_exists() for interfaces, trait_exists() for traits, and enum_exists() for enums.

Is class_exists case-sensitive?

No. PHP class names are case-insensitive, so class_exists('invoice') and class_exists('Invoice') both return true. Only the namespace separators and the fully qualified path matter.

More examples

Guarding a dynamic instantiation

The guard turns an unrecoverable fatal Error from new $class into a catchable exception with a useful message. Without class_exists(), the 'xml' call would abort the script.

Example · php
<?php
class JsonExporter {
    public function export(array $rows): string { return json_encode($rows); }
}

function makeExporter(string $format): object {
    $class = ucfirst($format) . 'Exporter';
    if (!class_exists($class)) {
        throw new InvalidArgumentException("No exporter for '$format'");
    }
    return new $class();
}

echo makeExporter('json')->export(['id' => 7]), "\n";
try { makeExporter('xml'); } catch (InvalidArgumentException $e) { echo $e->getMessage(), "\n"; }

Checking every kind of type declaration

Each name matches exactly one checker, except Level, which reports as both a class and an enum because enums are implemented as classes internally.

Example · php
<?php
interface Cache {}
trait Loggable {}
enum Level { case Warn; }
class FileCache implements Cache { use Loggable; }

foreach (['FileCache', 'Cache', 'Loggable', 'Level'] as $name) {
    printf("%-10s class:%d interface:%d trait:%d enum:%d\n",
        $name, class_exists($name), interface_exists($name),
        trait_exists($name), enum_exists($name));
}

Discussion

  • Be the first to comment on this lesson.