Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP closure function appended to stdObject and chained [duplicate]

Possible Duplicate:
Calling closure assigned to object property directly

If I have a class like this:

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?'

So my question is, when I call function two from function one, function two returns the $test variable which has a closure function of func() attached to it. Why can I not call that as a chained method?

Edit I just remembered that this can also be done by using $this->func->__invoke() for anyone that needs that.

like image 563
Senica Gonzalez Avatar asked Jan 12 '12 15:01

Senica Gonzalez


1 Answers

Because this is currently a limitation of PHP. What you are doing is logical and should be possible. In fact, you can work around the limitation by writing:

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

or

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

Stupid, I know.

like image 66
Jon Avatar answered Oct 19 '22 22:10

Jon