Check if a class exists with PHP

Posted in PHP -

PHP has the class_exists() function to check if a class has already been defined. You may need to take action depending if a class exists or not, and need to watch out for "gotchas" when also using __autoload().

Basic Usage

This is how it works:

if(class_exists('foo')) {
  ... do something ...
}
else {
  ... do something else ...
}

Or if you only want to test if the class doesn't exist, then just do this:

if(!class_exists('foo')) {
  ... do something ...
}

You can actually declare a class within those curly braces like this:

if(!class_exists('foo')) {
  class foo {
    function bar() {
      echo 'foo';
    }
  }
}

But you might instead include a file with the class definition etc or take some other action required if the class does not exist.

__autoload gotcha

PHP 5 introduced the __autoload() magic function (which I have written about already) and added a second parameter to the class_exists() function which is whether or not to call the __autoload function when checking to see if the class exists. The default is true, which maintains backward compatibility.

The reason I've called this a "gotcha" is it "got me" just yesterday when I was using the class_exists function inside __autoload and it was causing errors because the naming of the particular class didn't match what my __autoload was trying to do.

It took me a while to work out what the problem was but it was actually quite fortunate the class and file trying to autoload didn't match my naming convention becuase it alerted me to the issue and also would have meant it was loading an uncessary class file.

If you don't want autoload to automatically load the class file when using class_exists, pass false as the second parameter like so:

if(class_exists('foo', false)) {
  ... do something ...
}


Related posts:


Comments