PHP: Check if a class exists.

This is a short guide on how to check if a PHP class exists or not. This can be particularly handy if your code needs to detect whether certain PHP extensions are not installed or not.

Memcached.

Memcached is a memory caching system that allows you to cache the results of database queries. As a result, it can significantly speed up page load times.

In my case, I needed to detect whether the Memcache class was defined or not. If the class was not defined, I needed the caching mechanism in my script to fail gracefully.

Basically: If Memcache exists, “Great, let’s cache the results!” If not, “Well, OK then, let’s just power on regardless.”

The class_exists function.

Thankfully, PHP has a helpful function called class_exists, which allows you to check if a certain class has been defined or not.

Below, you will find an example of this function being used:

//Set it to FALSE by default.
$memcache = false;

//Check to see if a PHP class called Memcache exists.
if(class_exists('Memcache')){
    //It exists - attempt to connect.
    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211);
}

In the code above, I assume that the Memcache extension has not been installed unless the class_exists function proves me wrong.