7

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.

Community
  • 1
  • 1
Senica Gonzalez
  • 7,666
  • 15
  • 62
  • 106

1 Answers1

6

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.

hakre
  • 184,866
  • 48
  • 414
  • 792
Jon
  • 413,451
  • 75
  • 717
  • 787