Binding object instances to static closures Binding object instances to static closures php php

Binding object instances to static closures


PHP always binds the parent this and scope to newly created closures. The difference between a static closure and a non-static closure is that a static closure has scope (!= NULL) but not this at create time.A "top-level" closure has neither this nor scope.

Therefore, one has to get rid of the scope when creating the closure. Fortunately bindTo allows exactly that, even for static closures:

$m=(new ReflectionMethod('TestClass','testMethod'))->getClosure()->bindTo(null,null);$m();


Looks like this may not be possible, from Closure::bindTo documentation

Static closures cannot have any bound object (the value of the parameter newthis should be NULL), but this function can nevertheless be used to change their class scope.