PHP 7: Immediately Invoked Function Expressions


PHP7 will continue to borrow some of the beloved JavaScript features and will support Immediately Invoked Function Expressions (IIFEs):

echo (function() {
    return 42;
Output for php7@20140901 - 20141101:

Currying (functions returning functions) is also possible in combination with the IIFE implementation:

$foo = (function() {
    return function($a) {
        return $a + 42;

echo $foo(10);
Output for php7@20140901 - 20141101:

Note that when accessing an outer variable from within a function (aka “inheriting variables from outer scope”), one – unlike in JavaScript – needs to use the use keyword to make that variable accessible:

$foo = (function($a) {
    return function($b) use ($a) {
        return $a + $b;
echo $foo(10);
Output for php7@20140901 - 20141101:

/me is excited!

PHP7 IIFE Demo →
PHP7 Currying Demo →
PHP7 Currying Redux Demo →


Elsewhere , ,

5 Responses to PHP 7: Immediately Invoked Function Expressions

  1. Chris says:

    I was just trying to do this in PHP today and was a little sad finding out that you can’t. But I’m very glad to see these changes coming! (soon?)

    • Lionel says:


      call_user_func(function () {
      echo ';)';

      • Saddam says:

        Bro good job. I can execute logical expression with your IIFE –

        $a = [‘no’,’no’, ‘yes’, ‘np’, 787];
        if (in_array(‘yes’, $a)) echo “hello”;


        in_array(‘yes’, $a) && call_user_func(function() {
        echo “hello”;

  2. Random Interloper says:

    This is great, PHP is heading in the right direction. However the example you give is not actual currying. A better term for it would be partial application. Currying is a more specific subset of that behavior. I found a great stackoverflow post that explains it well and saves me having to explain it, so here:

  3. Pingback: Getting Ready for PHP 7 |

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.