PHP Tutorial - PHP class_exists() function






class_exists() returns true if the specified class is defined.

Syntax

bool class_exists ( string $class_name [, bool $autoload = true ] )

Parameters

  • class_name - The class name. The name is matched in a case-insensitive manner.
  • autoload - Whether or not to call __autoload by default.




Return Values

Returns TRUE if class_name is a defined class, FALSE otherwise.

Example 1

Check that the class exists before trying to use it


<?php
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>




Example 2

autoload parameter example


<?php//ww w.j  a v a  2s .c om
function __autoload($class)
{
    include($class . '.php');

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

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

?>