|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-04-26 13:22 UTC] jon at sprig dot gs
Description: ------------ --- From manual page: http://www.php.net/functions.anonymous --- The example #3 in Anonymous functions (relating to closures and scoping) is overly complex and doesn't explain what a closure is or how it would work. Perhaps something similar to the following may be more useful? Test script: --------------- <?php $external = 'world'; $anonymousfunction = function ($internal) { echo $internal . ' ' . $external . "\r\n"; } $anonymousfunction("hello"); // Will return "hello " and probably a PHP Notice that $external hasn't been set. $closurefunction = function ($internal) use ($external) { echo $internal . ' ' . $external . "\r\n"; } $closurefunction("hello"); // Will return "hello world" $closurefunctionwithpointer = function ($internal) use (&$external) { $external = $internal; } echo $external . "\r\n"; // Will return "world" $closurefunctionwithpointer("hello"); echo $external . "\r\n"; // Will return "hello" ?> Expected result: ---------------- hello PHP Notice: Undefined variable $external hello world world hello PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 11:00:02 2025 UTC |
I should add, having just seen something on StackOverflow, there should be another case to list in that example: <?php $external = 'world'; $closurefunction = function ($internal) use ($external) { echo $internal . ' ' . $external . "\r\n"; } $external = 'town'; $closurefunction("hello"); // Will return "hello town" ?> I don't know if this is indeed the case, but that's what the comment here: http://stackoverflow.com/questions/1065188/in-php-5-3-0-what-is-the-function-use-identifier-should-a-sane-programmer-us#comment885456_1066219 suggestsErrr, oops, that was supposed to show $closurefunction("hello"); // You may expect "hello town", but it will return "hello world" still because the use ($vars) is as per when it is defined, not when it is called.