[PHP] 無名関数への値の受け渡し方サンプル

PHP

array_map()の場合

<?php $a = 2; $b = 4; $arr = [1,2,3,4,5]; $res = array_map(function($num=[]) use($a, $b){ return [ "a" => $num * $a, "b" => $num * $b, ]; } , $arr); echo "<pre>"; print_r($res);

実行結果

Array ( [0] => Array ( [a] => 2 [b] => 4 ) [1] => Array ( [a] => 4 [b] => 8 ) [2] => Array ( [a] => 6 [b] => 12 ) [3] => Array ( [a] => 8 [b] => 16 ) [4] => Array ( [a] => 10 [b] => 20 ) )

無名関数への受け渡し

<?php $a = 2; $b = 4; $c = function($num=0) use($a, $b){ return [$num * $a , $num * $b]; }; print_r($c(100));

実行結果

Array ( [0] => 200 [1] => 400 )