【问题标题】:Calling a method (stored in a variable) in a closure在闭包中调用方法(存储在变量中)
【发布时间】:2015-01-08 10:36:32
【问题描述】:

如果可能,我正在尝试找到一种方法来使示例 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->getPayment()$o->Payment()有什么区别?
  • 没有区别,但它可以稍后删除,所以现在不是问题。
  • 顺便说一句,Closures disallow 直接实例化。

标签: php closures


【解决方案1】:
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());

【讨论】:

  • use ($method) 对其进行了排序。谢谢
【解决方案2】:

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

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


这应该有效:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2016-08-27
    相关资源
    最近更新 更多