News for hackers. Stuff that matters.
Re:Closure Object Binding in PHP 5.4 by deweller on Wednesday October 26, 2011 @11:35AM (#3159001)
I think a good use case is to solve the problem of calling a closure and passing $this.

In PHP 5.3, this is not allowed:

    class MyClass {

      public function doSomething() {
        $delegate = new SomeDelegateClass();

        // the following line is not allowed
        $delegate->doSomethingWithClosure(function($app) use ($this) {
         // do something with $app
        });
    }
You can now solve this problem simply with the bindTo method.
Re:Closure Object Binding in PHP 5.4 by Udo on Wednesday October 26, 2011 @12:10PM (#3159184)
I'm not sure I understand the underlying problem, but apparently you want $delegate->doSomethinWithClosure() to invoke the closure from the context of the current MyClass instance?

So here's how you could solve this "problem" before bindTo(), it's explicit and simple and it doesn't even need use:

  class SomeDelegateClass {
     
    function doSomethingWithClosure($callerObj, $closure) {
      $closure($callerObj);
    }
     
  }

  class MyClass {

    function hello() { print('hello from MyClass!'); }

    function doSomething() {

      $delegate = new SomeDelegateClass();
      $delegate->doSomethingWithClosure($this, function($myClassObj) {
          $myClassObj->hello();
        });

    }
    
  }