note 100545 added to functions.anonymous

From: Date: Fri, 22 Oct 2010 14:00:10 +0000
Subject: note 100545 added to functions.anonymous
Groups: php.notes 
Request: Send a blank email to php-notes+get-173373@lists.php.net to get a copy of this message
As an alternative to gabriel's recursive construction, you may instead assign the recursive function to a variable, and use it by reference, thus: <?php $fib = function($n)use(&$fib) { if($n == 0 || $n == 1) return 1; return $fib($n - 1) + $fib($n - 2); }; echo $fib(10); ?> Hardly a sensible implementation of the Fibonacci sequence, but that's not the point! The point is that the variable needs to be used by reference, not value. Without the '&', the anonymous function gets the value of $fib at the time the function is being created. But until the function has been created, $fib can't have it as a value! It's not until AFTER the function has been assigned to $fib that $fib can be used to call the function - but by then it's too late to pass its value to the function being created! Using a reference resolves the dilemma: when called, the anonymous function will use $fib's current value, which will be the anonymous function itself. At least, it will be if you don't reassign $fib to anything else between creating the function and calling it: <?php $fib = function($n)use(&$fib) { if($n == 0 || $n == 1) return 1; return $fib($n - 1) + $fib($n - 2); }; $lie = $fib; $fib = function($n) { return 100; }; echo $lie(10); // 200, because $fib(10 - 1) and $fib(10 - 2) both return 100. ?> Of course, that's true of any variable: if you don't want its value to change, don't change its value. All the usual scoping rules for variables still apply: a local variable in a function is a different variable from another one with the same name in another function: <?php $fib = function($n)use(&$fib) { if($n == 0 || $n == 1) return 1; return $fib($n - 1) + $fib($n - 2); }; $bark = function($f) { $fib = 'cake'; // A totally different variable from the $fib above. return 2 * $f(5); }; echo $bark($fib); // 16, twice the fifth Fibonacci number ?> ---- Server IP: 69.147.83.197 Probable Submitter: 125.239.226.127 ---- Manual Page -- http://www.php.net/manual/en/functions.anonymous.php Edit -- https://master.php.net/note/edit/100545 Del: integrated -- https://master.php.net/note/delete/100545/integrated Del: useless -- https://master.php.net/note/delete/100545/useless Del: bad code -- https://master.php.net/note/delete/100545/bad+code Del: spam -- https://master.php.net/note/delete/100545/spam Del: non-english -- https://master.php.net/note/delete/100545/non-english Del: in docs -- https://master.php.net/note/delete/100545/in+docs Del: other reasons-- https://master.php.net/note/delete/100545 Reject -- https://master.php.net/note/reject/100545 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#173373) next »