我正在开发一个项目,我正在使用旧版本的一些弃用函数.但是如果在旧版本中使用,则不希望我的脚本被停止.所以我正在检查函数是否存在,如果不存在则再次创建它.
但是function_exists和is_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::methodarray("Foo", "method")array($obj, "method")所以is_callable接受你可以通过的任何事情call_user_func和家庭,而function_exists只是告诉某个函数是否存在(不是方法,请参阅method_exists,也不是闭包).
换句话说,is_callable是一个包装器zend_is_callable,它使用伪类型回调处理变量,而function_exists只在函数表中进行哈希表查找.
cod*_*ict 12
当与函数(不是类方法)一起使用时,除了function_exists稍快一点之外没有区别.
但是当用于检查类中存在的方法时,您无法使用function_exists.你必须使用is_callable或method_exists.
小智 9
在类上下文中使用时is_callable,对于可访问的类方法(即公共方法)method_exists返回true,但对所有方法(public,protected和private)返回true.function_exists与method_exists外类背景相同.