Skip to content

Instantly share code, notes, and snippets.

@ritalin
Last active December 10, 2015 05:09
Show Gist options
  • Save ritalin/4385119 to your computer and use it in GitHub Desktop.
Save ritalin/4385119 to your computer and use it in GitHub Desktop.
phpのarray_mapのクロージャって、レキシカル変数を束縛しないの? 諸元 php 5.4.10 (none thread-safe) win7
<?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)
// }
<?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