PHP发送方法调用作为方法的参数

时间:2018-03-14 10:11:37

标签: php

我在很多方法中都有以下代码模式:

    $attempts = 0;

    do {

    $response = $this->DOSOMETHIING($data, $info);

    sleep(1);

    $attempts++;

    } while ($attempts < 5);

我想要做的是为这个while循环提供一个帮助器方法,可以某种方式发送一个特定的方法调用。所以像这样:

$response = $this->execute($this->DOSOMETHIING($data, $info));

辅助方法:

function execute($method){

$attempts = 0;

    do {

    $response = $method(); <<< I know!

    sleep(1);

    $attempts++;

    } while ($attempts < 5);

 return $response;

}

麻烦的是发送给helper方法的方法调用将是3种不同的方法调用之一,它们都有不同数量的参数,所以我不能单独发送方法和参数。

2 个答案:

答案 0 :(得分:3)

看起来你需要封闭模式:http://php.net/manual/en/class.closure.php

下面的代码对两种特征使用相同的“执行”功能:

public function __construct() {

}

public function execute($method) {
    $attempts = 0;
    do {
        $response = $method();
        sleep(1);
        $attempts++;
    } while ($attempts < 5);
    return $response;
}

public function foo($data, $info) {
    //Do something
    return array_merge($data,$info);
}

public function bar($other) {
    echo 'Hello '.$other;
}

public function main() {
    $data = ['foo' => 'bar'];
    $info = ['some' => 'info'];
    $other = 'world';

    $return = $this->execute(function() use ($data, $info) {
        return $this->foo($data,$info);
    });   
    var_dump($return);
    $this->execute(function() use ($other) {
        $this->bar($other);
    });
}
}

$tester = new Foo();
$tester->main();

答案 1 :(得分:1)

您可以使用call_user_func_array来返回回调的值。

相关问题