I am working on a project, in which I am using a deprecated function from the older version. But don't want my script to stop if used in the older version.
So I am checking if the function exists and if not then create it.
What is the difference between function_exists and is_callable in PHP and which one is better to use?
if (!is_callable('xyz')) { function xyz() { // code goes here } } OR
if(!function_exists('xyz')) { function xyz() { // code goes here } }
The function_exists() is an inbuilt function in PHP. The function_exists() function is useful in case if we want to check whether a function() exists or not in the PHP script. It is used to check for both built-in functions as well as user-defined functions. Syntax: boolean function_exists($function_name)
Use the PHP method_exists() function to check if an object or a class has a specified method.
The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.
The method_exists() function returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.
The function is_callable accepts not only function names, but also other types of callbacks:
Foo::methodarray("Foo", "method")array($obj, "method")So is_callable accepts anything that you could pass call_user_func and family, while function_exists only tells if a certain function exists (not methods, see method_exists for that, nor closures).
Put another way, is_callable is a wrapper for zend_is_callable, which handles variables with the pseudo-type callback, while function_exists only does a hash table lookup in the functions' table.
When used with a function (not a class method) there is no difference except that function_exists is slightly faster.
But when used to check the existence of methods in a class you cannot use function_exists. You'll have to use is_callable or method_exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With