50) { return str_replace ($search, $replacement, $text); } else { return $text; } }; return array_map ($map, $array); } var_dump(replace_in_array('aaa', 'bbb', array('aaaccc', 'ccccccccccthistextshouldbereplacedbynewtextreplacedaaa'))); $lprint("Closure lifetime"); function getAdder($x) { return function ($y) use ($x) { // or: lexical $x; return $x + $y; }; } $adder = getAdder(1); var_dump($adder(2), $adder(3)); $lprint("References vs. Copies"); $x = 1; $lambda1 = function () use ($x) { $x *= 2; }; $lambda2 = function () use (&$x) { $x *= 3; }; $lambda1 (); var_dump ($x); // gives: 1 $lambda2 (); var_dump ($x); // gives: 3 $lprint("Interaction with OOP"); class Example { private $search; public $x = 4; 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); }; } public static function staticClosure () { $x = 4; $closure = static function ($y) use ($x) { return $x + $y; }; return $closure (6); } public function __invoke () { echo "Hello World!\n"; } static function staticPrinter () { echo "Hello World!\n"; } function printer () { echo "Hello World: $this->x!\n"; } } $example = new Example ('hello'); $replacer = $example->getReplacer ('goodbye'); echo $replacer ('hello world'), "\n"; // goodbye world $example->setSearch ('world'); echo $replacer ('hello world'), "\n"; // hello goodbye var_dump(Example::staticClosure()); $lprint("Additional goody: __invoke"); $foo = new Example; $foo (); $lprint("Interaction with reflection: static"); $class = new ReflectionClass ('Example'); $method = $class->getMethod ('staticPrinter'); $closure = $method->getClosure (); $closure (); $lprint("Interaction with reflection: dynamic"); $class = new ReflectionClass ('Example'); $method = $class->getMethod ('printer'); $object = new Example; $closure = $method->getClosure ($object); $closure (); $object->x = 5; $closure ();