【问题标题】:PHP closure function appended to stdObject and chained [duplicate]PHP闭包函数附加到stdObject并链接[重复]
【发布时间】:2012-02-08 21:21:57
【问题描述】:

可能重复:
Calling closure assigned to object property directly

如果我有这样的课程:

class test{
  function one(){
     $this->two()->func(); //Since $test is returned, why can I not call func()?
  }

  function two(){
    $test = (object) array();
    $test->func = function(){
       echo 'Does this work?';
    };
    return $test;
  }
}

$new = new test;
$new->one(); //Expecting 'Does this work?'

所以我的问题是,当我从函数一调用函数二时,函数二返回 $test 变量,该变量附加了一个 func() 闭包函数。为什么我不能将其称为链式方法?

编辑 我只记得这也可以通过对任何需要的人使用 $this->func->__invoke() 来完成。

【问题讨论】:

    标签: php closures chaining


    【解决方案1】:

    因为这是目前 PHP 的一个限制。你正在做的事情是合乎逻辑的,应该是可能的。实际上,您可以通过以下方式解决限制:

    function one(){
        call_user_func($this->two()->func);
    }
    

    function one(){
        $f = $this->two()->func;
        $f();
    }
    

    愚蠢,我知道。

    【讨论】:

    • 嘿,有趣。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2021-06-20
    相关资源
    最近更新 更多