LoginSignup
1
1

More than 5 years have passed since last update.

レキシカルスコープ変数の意味とか使い方が良くわからなかったのでメモ

Posted at

・失敗例

$message = 'hello';

// "use" がない場合
$example = function () {
    var_dump($message);
};
$example();
Notice: Undefined variable: message in /example.php on line 6
NULL

・成功例

$message = 'hello';

// useを使う場合、$message を引き継ぎます
$example = function () use ($message) {
    var_dump($message);
};
$example();

// 引き継がれた変数の値は、関数が定義された時点のものであり、
// 関数が呼ばれた時点のものではありません
$message = 'world';
$example();
string(5) "hello"
string(5) "hello"

参考
http://php.net/manual/ja/functions.anonymous.php

1
1
0

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
1