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

even better, you can surround the class and method reference in parentheses and call normally.

Example:

    $c = new stdClass;
    $c->test = function() { return 'hello world'; };
    echo ($c->test)();



It's less obvious though, you need to know what's happening and why. Likely not a problem for somebody writing a lot of JS, but I rarely see similar constructs in PHP code.


I guess it's a little less known but you also have to use the same technique to immediately invoke a method on a constructed object, eg.

    $response = (new Response())->handle ();
So it's not completely alien in PHP.


That's true, and probably depends on the code base.

I don't know how these patterns develop - it's very common in JS, but somewhat rare in PHP. Maybe it has to do with the average level of the programmer in each? Or jQuery's noConflict() helped it along with everybody starting with (function($) {})(jQuery), thus integrating IIFE into their active repertoire.

I don't remember (and haven't found in quickly searching) PSR saying anything about that, but that could explain a difference in usage, too.


Most PHP codebases simply don't have much use for IIFE's. A well-maintained project will be neatly organized into namespaces and classes, and undefined variables don't automatically become global. Meanwhile, PSR-1 says that a file that defines classes and/or functions should not have any side effect. So you don't have to worry about accidentally interacting with other scopes.

Anonymous functions and classes are being used more and more, but PHP isn't fundamentally event-driven like JS so there's less need to hand them out like candy and nest them several levels deep. Most of the closures I do use on a daily basis are callback functions to things like array_filter() and preg_replace_callback(), not event handlers like every jQuery code ever written.


I think it's well known by most developers using PHP. You can do the same to call a function on a newly created object.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: