On Fri, May 31, 2013 at 10:54 AM, Nathaniel Higgins <n...@nath.is> wrote:

> Is it possible to bind an instance to a static closure, or to create a
> non-static closure inside of a static class method?
>

PHP doesn't have a method to do this. In JavaScript you can use jQuery's

    var func = $.proxy(function () { ... }, object);

In fact, you cannot use $this inside a closure at all (unless 5.4 has added
a way that I haven't seen yet). You can get around that by declaring a
local variable to hold a reference to the instance to use with "use". It
looks strange here because you're also passing in $testInstance for the
comparison.

    <?php
    class TestClass {
        public static function testMethod() {
            $testInstance = new TestClass();
            $closure = $testInstance->createClosure($testInstance);

            call_user_func($closure);
            // should be true
        }

        private function createClosure($testInstance) {
            $self = $this;
            return function() use ($self, $testInstance) {
                return $self === $testInstance;
            }
        }
    }

    TestClass::testMethod();

Peace,
David

Reply via email to