is_calleable、function_exits与method_exits函数用法

bool is_callable ( mixed $var [, bool $syntax_only [, string $callable_name ]] )

is_calleable是测参数是否为合法的可调用结构
第一个参数可以是函数名,可以是类或对象和方法数组。
第二个参数是否对方法名只做语法检查,不判断是否可以调用,默认false
第三个参数是将调用的名称传人一个变量中,感觉不咋常用

//判断方法是否能调用
function test(){};
$a = function(){};
$b = "test";
var_dump(is_callable("test")); //true
var_dump(is_callable($a)); //true
var_dump(is_callable($b)); //true
var_dump(is_callable("mock")); //false  一个不存在的函数
var_dump(is_callable("mock", true)); //true 只检查函数的语法

class TestClass
{
    public function testMethod(){}
    protected function protectedMethod(){} 
    private function privateMethod(){} 
}
$obj = new TestClass(null);
var_dump(is_callable(array("TestClass", 'testMethod')));//true 类方法
var_dump(is_callable(array($obj, 'testMethod')));//true 对象方法
var_dump(is_callable(array("TestClass", 'testMethod2')));//false 不存在的类方法
var_dump(is_callable(array("TestClass", 'testMethod2'), true));//true
var_dump(is_callable(array("TestClass", 'protectedMethod')));//false 受保护的类方法
var_dump(is_callable(array("TestClass", 'protectedMethod'), true));//true 只检查语法 
var_dump(is_callable(array("TestClass", 'privateMethod')));//false 私有类方法
var_dump(is_callable(array("TestClass", 'privateMethod'), true));//true
var_dump(is_callable(array($obj, 'privateMethod'), false, $name));//true 
echo $name;//TestClass::privateMethod

function_exists (string$function_name )
从参数可以看出传人的是一个函数的名字,不能传类或者对象方法。

bool method_exists ( object $object , string $method_name )
判断类或者对象方法是否存在,手册上object得类型提示有些不准确,传类的名字作为参数其实也行。

class TestClass
{
    public function testMethod(){}
    protected function protectedMethod(){} 
    private function privateMethod(){} 
}
$obj = new TestClass(null);
var_dump(method_exists($obj, "testMethod"));//true 类方法
var_dump(method_exists("TestClass", "testMethod"));//true 类方法
var_dump(method_exists("TestClass", "protectedMethod"));//true受保护类方法
var_dump(method_exists("TestClass", "privateMethod"));//true私有类方法
is_callable和method_exits在判断类方法时有一个区别,默认下is_callable函数要判断该方法能不能被正常调用,想protected和private方法返回的都是false,而method_exits就如它的名字所示,只是判断该方法是否存在,而不管能不能调用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值