class_exists
Checks whether a class is defined.
Syntax
class_exists(string $class, bool $autoload = true): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $class | string | The full class name. |
| $autoload | bool | Optional. Whether to try loading the class with the autoloader. |
Return value
bool`true` if the class exists.
Examples
A built-in and a missing class:
<?php
var_dump(class_exists('DateTime'));
var_dump(class_exists('App\\Models\\Unknown'));Output:
bool(true)
bool(false)Notes
The name is given in full, with its namespace. It is more reliable to write it with ::class: class_exists(User::class).
See also
- method_exists — Checks whether a class or an object has a method.
- function_exists — Checks whether a function is defined.
- spl_autoload_register — Registers a function that loads a class file the first time the class is used.
Related recipes
In the tutorial
- Namespaces and Composer — How a PHP project is organised — namespaces, PSR-4 class autoloading and installing libraries with Composer.