LoginSignup
13
11

More than 5 years have passed since last update.

PHPのクロージャーで、呼び出し元の変数を使う

Last updated at Posted at 2012-01-30

PHPのarray関連の関数でクロージャーを使う場合の話。

例えば、ある関数に引数を渡して、その引数の値以上の結果を返す場合。

//NG
function filterResultsNG($threshold) {
    $all = array(2,0,-1,3,4,-5);
    return array_filter($all, function($v) {
                return $v >= $threshold;
            });
}

//useを使うとOK
function filterResults($threshold) {
    $all = array(2,0,-1,3,4,-5);
    return array_filter($all, function($v) use ($threshold) {
                return $v >= $threshold;
            });
}
13
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11