Using the PHP class_exists() Function

Checks whether the specified class name is defined.

Let's check if there is an example class.


class Test {}

var_dump(class_exists('test')); // Result: bool(true)
var_dump(class_exists('phpExample')); // Result: bool(false)

Example of use with auto-loading classes.


spl_autoload_register(function ($className) {
    $classFile = "classes/" . strtolower($className) . '.php';
    if (file_exists($classFile))
        include $classFile;

// Result: bool(true)
// Because the 2nd parameter is true by default and is in the control process with the help of automatic class load function above know class has
// Of course, in this example, we assume you have "classes / test.php" file and Test class in it.


// Result: bool(false)
// Because we closed the autoload event, so it can't find it because it can't load the class and the class is called automatically.

var_dump(class_exists('test', false));

See you in our next article :)


There are no comments, make the firs comment