Re: [PHP] Binding object instances to static closures

[email protected] (David Harkness)
Newsgroups php.general
Message-ID <CAO8qQL=pVfxNU6xfB8M7sTZ9CZB0zeuPg-wxhVaAYVzj1bJdEw@mail.gmail.com>
On Fri, May 31, 2013 at 10:54 AM, Nathaniel Higgins <[email protected]> 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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.