PHP中的is_callable和function_exists之间究竟有什么区别?

Che*_*rma 43 php

我正在开发一个项目,我正在使用旧版本的一些弃用函数.但是如果在旧版本中使用,则不希望我的脚本被停止.所以我正在检查函数是否存在,如果不存在则再次创建它.

但是function_existsis_callablephp 之间有什么区别,哪一个对用户更好?

if(!is_callable('xyz')) {

  function xyz() {
    // code goes here
  }
}
Run Code Online (Sandbox Code Playgroud)

要么

if(!function_exists('xyz')) {

  function xyz() {
    // code goes here
  }
}
Run Code Online (Sandbox Code Playgroud)

Art*_*cto 54

该函数is_callable不仅接受函数名称,还接受其他类型的回调:

  • Foo::method
  • array("Foo", "method")
  • array($obj, "method")
  • 闭包和其他可调用对象(PHP 5.3)

所以is_callable接受你可以通过的任何事情call_user_func和家庭,而function_exists只是告诉某个函数是否存在(不是方法,请参阅method_exists,也不是闭包).

换句话说,is_callable是一个包装器zend_is_callable,它使用伪类型回调处理变量,而function_exists只在函数表中进行哈希表查找.


cod*_*ict 12

当与函数(不是类方法)一起使用时,除了function_exists稍快一点之外没有区别.

但是当用于检查类中存在的方法时,您无法使用function_exists.你必须使用is_callablemethod_exists.


小智 9

在类上下文中使用时is_callable,对于可访问的类方法(即公共方法)method_exists返回true,但对所有方法(public,protected和private)返回true.function_existsmethod_exists外类背景相同.