Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

class_exists

Checks whether a class is defined.

Syntax

class_exists(string $class, bool $autoload = true): bool

Parameters

ParameterTypeDescription
$classstringThe full class name.
$autoloadboolOptional. 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

Related recipes

In the tutorial

  • Namespaces and Composer — How a PHP project is organised — namespaces, PSR-4 class autoloading and installing libraries with Composer.

Thanks for reading!

Donate to the site — we work hard for you.