Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the difference between the is_callable and function_exists in PHP?

Tags:

php

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     } } 
like image 215
Chetan Sharma Avatar asked Aug 17 '10 06:08

Chetan Sharma


People also ask

What is Function_exists function in PHP?

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)

How do you check if a class has a method PHP?

Use the PHP method_exists() function to check if an object or a class has a specified method.

Is callable in PHP?

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.

Is method exists PHP?

The method_exists() function returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.


2 Answers

The function is_callable accepts not only function names, but also other types of callbacks:

  • Foo::method
  • array("Foo", "method")
  • array($obj, "method")
  • Closures and other invokable objects (PHP 5.3)

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.

like image 152
Artefacto Avatar answered Oct 04 '22 15:10

Artefacto


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.

like image 44
codaddict Avatar answered Oct 04 '22 16:10

codaddict