tags:

views:

73

answers:

3

I am working on a project, in which i am using some deprecated function form the older version. But don't want my script to be stopped if used in the older version. So i am checking if the function exists and if it doesn't then creating it again.

But what is the difference between function_exists and is_callable in php and which one is better to user ?

if(!is_callable('xyz')) {

  function xyz() {
    // code goes here
  }
}

OR

if(!function_exists('xyz')) {

  function xyz() {
    // code goes here
  }
}
+1  A: 

If a function "Plop" exists then 'function_exists("Plop")' will return true.
http://us.php.net/manual/en/function.function-exists.php

If a variable is callable then is_callable($var) will return true.
Now this could mean that $var is a function name.
But i could also be an object and method name combo.
http://us3.php.net/manual/en/function.is-callable.php

Martin York
+5  A: 

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.

Artefacto
Thanks this helped alot..
Chetan sharma
+2  A: 

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.

codaddict