PHP回调/可调用对象详解

首页 / 新闻资讯 / 正文

定义和用法

回调是PHP中的伪类型。在PHP 5.4中,引入了Callable类型提示,类似于Callback。当某个对象被标识为可调用时,意味着它可以用作可调用的函数。可调用对象可以是内置的或用户定义的函数,也可以是任何类内的方法。

is_callable()函数可用于验证标识符是否可调用。PHP的call_user_function()接受函数名称作为参数。

以下示例显示了一个内置函数是可调用的。

示例

<?php var_dump (is_callable("abs")); ?>

输出结果

这将产生以下结果-

bool(true)

在以下示例中,测试了用户定义的函数是否可调用。

示例

<?php function myfunction(){    echo "Hello World"; } echo is_callable("myfunction") . "\n"; call_user_func("myfunction") ?>

输出结果

这将产生以下结果-

1 Hello World

为了将对象方法作为可调用方法传递,对象本身及其方法作为数组中的两个元素传递

示例

<?php class myclass{    function mymethod(){       echo "This is a callable" . "\n";    } } $obj=new myclass(); call_user_func(array($obj, "mymethod")); //array passed in literal form call_user_func([$obj, "mymethod"]); ?>

输出结果

这将产生以下结果-

This is a callable This is a callable

类中的静态方法也可以作为可调用方法传递。类的名称应该是数组参数中的第一个元素,而不是对象

示例

<?php class myclass{    static function mymethod(){       echo "This is a callable" . "\n";    } } $obj=new myclass(); call_user_func(array("myclass", "mymethod")); //using scope resolution operator call_user_func("myclass::mymethod"); ?>

输出结果

这将产生以下结果-

This is a callable This is a callable