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 .
Source: https://habr.com/ru/post/30126/
All Articles