2

I have a class

class SomeClass {
  private $someVar;

  public function Init($func) {
    $this->someVar = $func;
  }

  public function DoSomething() {
    $this->someVar("asdasdasd");
  }
}

$obj = new SomeClass();
$obj->Init(function ($param){var_dump($param);});
$obj->DoSomething();

When I call the method DoSomething, I get an error that SomeClass::someVar() is undefined method. But when I use the debugger, I see that it is a closure object. If I save the function into a local variable ($someVar without $this) and call it in the Init() function, it works just fine. But I don't want to call the function there. I want to call it later.

Even if I save it into $this->someVar and call it in the same scope it does not work.

peterh
  • 11,875
  • 18
  • 85
  • 108
Alexander Beninski
  • 817
  • 3
  • 11
  • 24
  • [already solved](http://stackoverflow.com/questions/7067536/how-to-call-a-closure-that-is-a-class-variable) – falinsky Jan 15 '12 at 22:28

3 Answers3

4

Maybe you should simply try this :

public function DoSomething()
{
  $tmpVar = $this->someVar;
  $tmpVar("asdasdasd");
}

or, if you prefer, this :

public function DoSomething()
{
  call_user_func($this->someVar, "asdasdasd");
}
greg0ire
  • 22,714
  • 16
  • 72
  • 101
  • 1
    call_user_func works slowly. 1 variant will work: http://codepad.viper-7.com/P5gEiN – OZ_ Jan 15 '12 at 22:29
0

Here you have other options: How to call a closure that is a class variable?

Basically:

    1. Force the call to the __invoke magic method:

      $myInstance = new MyClass(); $myInstance->lambda->__invoke();

  • Or 2. Capture the method call:

    class MyClass
    {
        private $lambda;
    
        public function __construct()
        {
            $this->lambda = function() {
                echo "Hello world!\n";
            };
        }
    
        public function __call($name, $args)
        {
            return call_user_func_array($this->$name, $args);
        }
    }
    
Community
  • 1
  • 1
JavierCane
  • 2,324
  • 2
  • 22
  • 19
0

Try

public function DoSomething()
{
    call_user_func( $this->someVar, 'test');
}
Vyktor
  • 20,559
  • 6
  • 64
  • 96