Hacker News new | comments | show | ask | jobs | submit login

Would have preferred something to enable more visually pleasing metaprogramming, like:

$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.




I am aware of the gnarliness of the following BUT You could do something like:

   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.


If you look at the RFC (https://wiki.php.net/rfc/closures/object-extension) it's in there.

But it ain't present in the current builds of 5.4, AFAIK. Don't know what's happened there...


You can use this:

    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)();


It doesn't even have to be 'sugar' like that.

$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.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: