Check if a PHP class exists

Josh Sherman
1 min read
Software Development PHP

We’ve discussed how to check if a class has a function but what if the class doesn’t exist at all? To check if a class exists you can use, use guessed it, class_exists().

if (class_exists('MyClass'))
{
	$object = new MyClass();
}
else
{
	throw new Exception('The class MyClass does not exist.');
}

As of PHP 5.0.0 the class_exists() function will attempt to use __autoload() to load the class if available. This default behavior can be overwritten by passing a second parameter of false to class_exists().

Also worth nothing, as of PHP 5.0.2 class_exists() will return false if you pass it an interface. When checking if an interface exists, you can use interface_exists().

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Engineering Manager and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles