by mgkimsal · 15y ago · 0 comments
$closure = function() {
echo $this->foo;
};
$context = new \StdClass;
$context->foo = "Hello World";
$context->closure = $closure;
$context->closure();
Not sure if this will be possible in 5.4, but haven't seen anything on it. Right now, we have to do
$context->closure = $closure;
$temp = $context->closure;
$temp();
which is kinda ugly.
class Object {
public function __call($method, $args) {
if(isset($this->$method) && $this->$method instanceof \Closure) {
$this->$method->bindTo($this);
return call_user_func_array($this->$method, $args);
}
}
}
$context = new Object;
$context->foo = "Hello World";
$context->closure = function() {
echo $this->foo;
};
$context->closure();
Once traits are in the language (5.5?) that could just be mixed in.But it ain't present in the current builds of 5.4, AFAIK. Don't know what's happened there...
call_user_func($context->closure);
But yeah, some syntactic sugar would sure be nice. I'd like to see this in a future version of PHP... ($context->closure)();$content->closure()
It could look at the registered methods, then scan for properties of that name that would be closures, then fall back to __call. You could add this to __call with __set() checks for assigned values being closures, but it's rather ugly to have to do that for all class definitions.