在闭包中调用方法(存储在变量中)


Calling a method (stored in a variable) in a closure

如果可能的话,我正在尝试找到一种方法使示例 2 工作。有人能帮我一把吗?

$this->getValue('getName');
$this->getValue('getEmail');

示例 1(作品)

private function getValue($method)
{
    $o = new Order();
    $p = $o->Payment();
    return $p->$method();                 // Works
    return  $p->call_user_func($method);  // Works
}

示例 2(不起作用)

private function getValue($method)
{
    return
        new Closure(function (Order $o) {
            if ($o->getPayment() instanceof Payment) {
                 return $o->Payment()->$method();                 // Don't Work
                 return $o->Payment()->call_user_func($method);   // Don't Work
            }
        });
}
class Test {
    public function abc(){
       echo "ok";
    }
}

function getValue($method){
    return (function($o) use ($method) {
        if ($o instanceof Test) {
            return $o->$method();
        }
    });
}
$m = getValue('abc');
$m(new Test());

$o是未定义的,您可能已经收到此错误消息:

Parse error: parse error, expecting `'&'' or `T_VARIABLE'

这应该有效:

private function getValue($method)
{
    return
        new Closure(function () {
            $o = new Order();
            return $o->Payment()->$method();
        });
}