Check if a PHP class has a certain function

We’ve previously discussed how to check if a function exists but that only works on standalone functions like the ones built into PHP as well as any user defined functions. Luckily there’s a function for that called method_exists(). When speaking in the scope of a class, the functions are referred to as class methods, even if the syntax is indicative of them being called functions.

Using method_exists() assumes you already have the object instantiated as it is one of the passed arguments along with the name of the function:

$object = new MyClass

if (method_exists($object, 'my_function'))
{
	$object->my_function
}
else
{
	throw new Exception('MyClass does not have a method named my_function()'
}

But what if you wanted to check if the function exists before the class is even instantiated? Perhaps the availability of the function is the only reason you’d want to instantiate the class. There’s no need for object bloat by instantiating a class you won’t be using, you can use get_class_methods() to pull a list of available functions from the class:

if (in_array('my_function', get_class_methods('MyClass')))
{
	$object = new MyClass
	$object->my_function
}
else
{
	throw new Exception('MyClass does not have a method named my_function()'
}

It’s worth pointing out that get_class_methods() can also accept an object or new class declaration as the argument instead of the name of the class.

But what if the class doesn’t even exist? You’ll have to wait for my next post 🙂

Josh Sherman - The Man, The Myth, The Avatar

About Josh

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


If you found this article helpful, please consider buying me a coffee.