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

后端 未结 5 1704
长发绾君心
长发绾君心 2021-02-01 01:22

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 check

相关标签:
5条回答
  • 2021-02-01 01:43

    One more different:

    If you have a class which uses __call magic method, the is_callable($object, $method) will always return true for anything because __call basically accepts every method name. And as you might already know, method_exists will return false for this if the method is not defined in the class.

    This is especially annoying if you use CakePHP Model class as they implemented __call magic method to provide magic queries, but not cool if you want the method to be absolutely defined.

    0 讨论(0)
  • 2021-02-01 01:56

    If a function Plop exists then function_exists("Plop") will return true.

    See function_exists

    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.

    See is_callable

    0 讨论(0)
  • 2021-02-01 01:58

    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.

    0 讨论(0)
  • 2021-02-01 01:59

    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.

    0 讨论(0)
  • 2021-02-01 02:01

    When used in class context, is_callable returns true for class methods that are accessible ie public methods but method_exists returns true for all methods - public, protected and private. function_exists does same thing as method_exists outside class contexts.

    0 讨论(0)
提交回复
热议问题