Re: Binding object instances to static closures

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, May 31, 2013 at 10:54 AM, Nathaniel Higgins <nat@xxxxxxx> 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

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux