如何在PHP中实现回调?

时间:2008-09-08 00:53:34

标签: php

如何用PHP编写回调?

9 个答案:

答案 0 :(得分:167)

本手册可互换地使用术语“回调”和“可调用”,但是,“回调”传统上是指一个字符串或数组值,其作用类似function pointer,引用函数或类方法以供将来调用。从PHP 4开始,这允许函数式编程的一些元素。口味是:

$cb1 = 'someGlobalFunction';
$cb2 = ['ClassName', 'someStaticMethod'];
$cb3 = [$object, 'somePublicMethod'];

// this syntax is callable since PHP 5.2.3 but a string containing it
// cannot be called directly
$cb2 = 'ClassName::someStaticMethod';
$cb2(); // fatal error

// legacy syntax for PHP 4
$cb3 = array(&$object, 'somePublicMethod');

这是一种通常使用可调用值的安全方法:

if (is_callable($cb2)) {
    // Autoloading will be invoked to load the class "ClassName" if it's not
    // yet defined, and PHP will check that the class has a method
    // "someStaticMethod". Note that is_callable() will NOT verify that the
    // method can safely be executed in static context.

    $returnValue = call_user_func($cb2, $arg1, $arg2);
}

现代PHP版本允许将上面的前三种格式直接调用为$cb()call_user_funccall_user_func_array支持以上所有内容。

请参阅:http://php.net/manual/en/language.types.callable.php

备注/注意事项:

  1. 如果函数/类是命名空间,则字符串必须包含完全限定名称。例如。 ['Vendor\Package\Foo', 'method']
  2. call_user_func不支持通过引用传递非对象,因此您可以使用call_user_func_array,或者在以后的PHP版本中,将回调保存到var并使用直接语法:{{1 }};
  3. 具有__invoke()方法的对象(包括匿名函数)属于“可调用”类别,可以使用相同的方式,但我个人并不将这些与传统的“回调”术语相关联。
  4. 遗留$cb()创建一个全局函数并返回其名称。它是create_function()的包装器,应该使用匿名函数。

答案 1 :(得分:65)

使用PHP 5.3,您现在可以执行此操作:

function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});

最后一个很好的方法来做到这一点。 PHP的一个很好的补充,因为回调很棒。

答案 2 :(得分:29)

回调的实现就像这样完成

// This function uses a callback function. 
function doIt($callback) 
{ 
    $data = "this is my data";
    $callback($data); 
} 


// This is a sample callback function for doIt(). 
function myCallback($data) 
{ 
    print 'Data is: ' .  $data .  "\n"; 
} 


// Call doIt() and pass our sample callback function's name. 
doIt('myCallback');

显示:数据是:这是我的数据

答案 3 :(得分:9)

我最近发现的一个很好的技巧是使用PHP的create_function()来创建一次性使用的匿名/ lambda函数。它对于array_map()preg_replace_callback()usort()等使用回调进行自定义处理的PHP函数很有用。它看起来非常类似于eval(),但它仍然是使用PHP的一种很好的功能方式。

答案 4 :(得分:7)

好吧......随着5.3的出现,一切都会好一些,因为5.3,我们将获得闭包,并使用匿名函数

http://wiki.php.net/rfc/closures

答案 5 :(得分:6)

您需要验证您的通话是否有效。例如,在特定功能的情况下,您需要检查并查看该功能是否存在:

function doIt($callback) {
    if(function_exists($callback)) {
        $callback();
    } else {
        // some error handling
    }
}

答案 6 :(得分:5)

create_function在课堂上对我不起作用。我不得不使用call_user_func

<?php

class Dispatcher {
    //Added explicit callback declaration.
    var $callback;

    public function Dispatcher( $callback ){
         $this->callback = $callback;
    }

    public function asynchronous_method(){
       //do asynch stuff, like fwrite...then, fire callback.
       if ( isset( $this->callback ) ) {
            if (function_exists( $this->callback )) call_user_func( $this->callback, "File done!" );
        }
    }

}

然后,使用:

<?php 
include_once('Dispatcher.php');
$d = new Dispatcher( 'do_callback' );
$d->asynchronous_method();

function do_callback( $data ){
   print 'Data is: ' .  $data .  "\n";
}
?>

[编辑] 添加了一个缺失的括号。 另外,添加了回调声明,我更喜欢它。

答案 7 :(得分:3)

每次我在php中使用create_function()时,我都会感到畏缩。

参数是一个逗号分隔的字符串,字符串中的整个函数体...... Argh ......我认为即使他们尝试过它们也不会让它变得更加丑陋。

不幸的是,它是创建命名函数不值得的唯一选择。

答案 8 :(得分:1)

对于那些不关心破坏与PHP < 5.4的兼容性的人,我建议使用类型提示来实现更清晰的实现。

function call_with_hello_and_append_world( callable $callback )
{
     // No need to check $closure because of the type hint
     return $callback( "hello" )."world";
}

function append_space( $string )
{
     return $string." ";
}

$output1 = call_with_hello_and_append_world( function( $string ) { return $string." "; } );
var_dump( $output1 ); // string(11) "hello world"

$output2 = call_with_hello_and_append_world( "append_space" );
var_dump( $output2 ); // string(11) "hello world"

$old_lambda = create_function( '$string', 'return $string." ";' );
$output3 = call_with_hello_and_append_world( $old_lambda );
var_dump( $output3 ); // string(11) "hello world"
相关问题