PHP class_exists() function

In this chapter you will learn:

  1. What is PHP class_exists() function
  2. Syntax for PHP class_exists() function
  3. Parameters for PHP class_exists() function
  4. Return Values
  5. Example - Check that the class exists before trying to use it
  6. Example - autoload parameter example

Description

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/*j  av  a2  s . c o m*/
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Example 2

autoload parameter example


<?php/*from   j  av a  2  s . com*/
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();
}

?>

Next chapter...

What you will learn in the next chapter:

  1. What is PHP get_class() function
  2. Syntax for PHP get_class() function
  3. Parameters for PHP get_class() function
  4. Return Values
  5. Example - Get the class name
Home » PHP Tutorial » PHP Class Functions
PHP class_exists() function
PHP get_class() function
PHP get_declared_classes() function
PHP get_declared_interfaces() function
PHP get_defined_functions() function
PHP instanceof
PHP serialize() function