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.
method_exists() assumes you already have the object instantiated as it is one of the passed arguments along with the name of the 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:
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 :)