Re: Binding object instances to static closures
| From: | David Harkness | Date: | Fri, 31 May 2013 18:25:01 +0000 |
| Subject: | Re: Binding object instances to static closures | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-321305@lists.php.net to get a copy of this message | ||
On Fri, May 31, 2013 at 10:54 AM, Nathaniel Higgins <nat@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