class_exists in PHP

Syntax of class_exists

bool class_exists(string name[, bool autoload_class])

Returns true if a class with the same name as the string has been defined; if not, it returns false. The comparison for class names is case-insensitive. If autoload_class is set and is true, the class is loaded through the class’s __autoload() function before getting the interfaces it implements.

Example of class_exists

<?php
// Check that the class exists before trying to use it
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

More Example of class_exists

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';

    // Check to see whether the include declared the class
    if (!class_exists($class_name, false)) {
        throw new LogicException("Unable to load class: $class_name");
    }
});

if (class_exists(MyClass::class)) {
    $myclass = new MyClass();
}

?>

Leave a Comment