Last active
December 10, 2015 05:09
-
-
Save ritalin/4385119 to your computer and use it in GitHub Desktop.
phpのarray_mapのクロージャって、レキシカル変数を束縛しないの? 諸元
php 5.4.10 (none thread-safe)
win7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$sum = 0; | |
var_dump( | |
array_map( | |
function($v) use ($sum) { $sum =+ $v; return $sum; }, | |
range(1, 10) | |
) | |
); | |
// results: | |
// array(10) { | |
// [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) | |
// [5]=> int(6) [6]=> int(7) [7]=> int(8) [8]=> int(9) [9]=> int(10) | |
// } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// レキシカル変数を参照渡しする必要があると、回答をいただきました | |
$sum = 0; | |
var_dump( | |
array_map( | |
function ($v) use (&$sum) { return $sum += $v;}, | |
range(1, 10) | |
) | |
); | |
// results: | |
// array(10) { | |
// [0]=> int(1) [1]=> int(3) [2]=> int(6) [3]=> int(10) [4]=> int(15) [5]=> int(21) | |
// [6]=> int(28) [7]=> int(36) [8]=> int(45) [9]=> int(55) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment