note 111164 added to language.variables.scope

From: Date: Mon, 21 Jan 2013 18:01:54 +0000
Subject: note 111164 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-193302@lists.php.net to get a copy of this message
An alternative to static variables is to use an anonymous function. Here's an example with a simple counter which goes up on each call: <?php // Static version $staticCounter = function() { // Make $a static, so its value is preserved static $a = 0; $a++; return $a; }; echo $staticCounter(); echo $staticCounter(); echo $staticCounter(); // Output: // 1 // 2 // 3 // Closure version $counterFactory = function () { // We *assign* $a in this function $a = 0; return function() use (&$a) { // Notice the & // We *use* $a in this function $a++; return $a; }; }; // The above is a 'counter factory'; when called it returns a counter $closureCounter1 = $counterFactory(); echo $closureCounter1(); echo $closureCounter1(); echo $closureCounter1(); // Output: // 1 // 2 // 3 // If we call our 'factory' again, we get another counter, independent of the first $closureCounter2 = $counterFactory(); echo $closureCounter1(); echo $closureCounter2(); echo $closureCounter1(); echo $closureCounter2(); // Output (notice that we're calling both counters) // 4 // 1 // 5 // 2 // We can do it with arguments too $makeCounterFrom = function($start) { return function() use (&$start) { $start++; return $start; }; }; $yearCounter = $makeCounterFrom(2012); echo $yearCounter(); echo $yearCounter(); // Output // 2013 // 2014 ?> This use of closures may be familiar from Javascript's 'one-shot' functions "(function() {...})()". In PHP we can do this on 2 lines using a variable, or with 'call_user_func'. It's useful when a regular function isn't enough, but a whole class is overkill. ---- Server IP: 69.147.83.199 Probable Submitter: 77.86.30.139 ---- Manual Page -- http://php.net/manual/en/language.variables.scope.php Edit -- https://master.php.net/note/edit/111164 Del: integrated -- https://master.php.net/note/delete/111164/integrated Del: useless -- https://master.php.net/note/delete/111164/useless Del: bad code -- https://master.php.net/note/delete/111164/bad+code Del: spam -- https://master.php.net/note/delete/111164/spam Del: non-english -- https://master.php.net/note/delete/111164/non-english Del: in docs -- https://master.php.net/note/delete/111164/in+docs Del: other reasons-- https://master.php.net/note/delete/111164 Reject -- https://master.php.net/note/reject/111164 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#193302) next »