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

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
            }
        });
}

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

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


这应该有效:

private function getValue($method)
{
    return
        new Closure(function () {
            $o = new Order();
            return $o->Payment()->$method();
        });
}
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());