1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPのmap()関数内でローカル変数を使う方法

Last updated at Posted at 2021-08-23

Laravelを使っていた際に外で定義した変数をmap()関数内でグローバル定義したにもかかわらず値がnullだったので調べたところ下記の記事を見つけました。

#間違え例

MainController.php
public function myloc(Request $request){
            $my_lat=$request->my_lat;
            $my_long=$request->my_lon;        

        $boxes->map(function($item,$key){
            global $my_lat,$my_long;

        $item['distance'] .= $item->distance1($my_lat,$my_long);
            return $item;

            });

 return view('index', ['boxes' => $boxes]);
    }

#修正後

MainController.php
public function myloc(Request $request){

            $my_lat=$request->my_lat;
            $my_long=$request->my_lon;        

        $boxes->map(function($item,$key) use ($my_lat,$my_long){

        $item['distance'] .= $item->distance1($my_lat,$my_long);
            return $item;

            });
 return view('index', ['boxes' => $boxes]);
    }

#結論
use()を使うことでmap()関数内でローカル変数を使えます。

グローバル変数だと思って関数内でグローバル定義しましたが関数の中に関数を書いているためuse()で引数を渡す必要があるみたいです。

1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?