📜 ⬆️ ⬇️

Lambda calculation and closure

At the end of 2007, a patch was added that adds lambda functions (but without closures) for PHP. During the discussion on the mailing list, it was decided that without the support of closures, there is no need to add them to PHP.
However, interest in this topic led to a significant change in the original patch by Christian Seiler and the release of a new patch by Dmitry Stogov.

As a result, we have the closure and lambda functions in PHP (5.3)




function getAdder ($ x) {
return function ($ y) use ($ x) {
// or: lexical $ x;
return $ x + $ y;
};
}
// ---- OOP
')
class Example {
private $ search;
public function __construct ($ search) {
$ this -> search = $ search;
}
public function setSearch ($ search) {
$ this -> search = $ search;
}
public function getReplacer ($ replacement) {
return function ($ text) use ($ replacement) {
return str_replace ($ this -> search, $ replacement, $ text);
};
}
}
$ example = new Example ( 'hello' );
$ replacer = $ example-> getReplacer ( 'goodbye' );
echo $ replacer ( 'hello world' ); // goodbye world
$ example-> setSearch ( 'world' );
echo $ replacer ( 'hello world' ); // hello goodbye

class Example {
public function __invoke () {
echo "Hello World! \ n" ;
}
}
$ foo = new Example;
$ foo ();

// --- Reflection

class Example {
static function printer () {echo "Hello World! \ n" ; }
}
$ class = new ReflectionClass ( 'Example' );
$ method = $ class -> getMethod ( 'printer' );
$ closure = $ method-> getClosure ();
$ closure (); * This source code was highlighted with Source Code Highlighter .


Looking forward to release PHP 5.3




Sources:


Upd: You can learn more about the benefits of these innovations in the documentation for languages ​​such as Erlang , ECMAScript , Ruby

It was possible to implement such functionality before , it is just “syntactic sugar”

Source: https://habr.com/ru/post/30126/


All Articles