PHP闭包函数附加到stdObject并链接

Sen*_*lez 7 php closures chaining

可能重复:
直接调用分配给对象属性的闭包

如果我有这样的课程:

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?'
Run Code Online (Sandbox Code Playgroud)

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

编辑 我记得这也可以通过对需要的人使用$ this-> func - > __ invoke()来完成.

Jon*_*Jon 6

因为这是目前PHP的限制.你在做什么是合乎逻辑的,应该是可能的.事实上,您可以通过编写来解决限制:

function one(){
    call_user_func($this->two()->func);
}
Run Code Online (Sandbox Code Playgroud)

要么

function one(){
    $f = $this->two()->func;
    $f();
}
Run Code Online (Sandbox Code Playgroud)

愚蠢,我知道.