Quantcast
Channel: php – Bram.us
Viewing all articles
Browse latest Browse all 166

PHP 7: Immediately Invoked Function Expressions

$
0
0

php-logo

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

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

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

<?php
$foo = (function() {
    return function($a) {
        return $a + 42;
    };
})();

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

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:

<?php
$foo = (function($a) {
    return function($b) use ($a) {
        return $a + $b;
    };
})(42);
echo $foo(10);
Output for php7@20140901 - 20141101:
52

/me is excited!

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

(via)


Viewing all articles
Browse latest Browse all 166

Trending Articles