# PHP - Anonymous functions (匿名函數) 經常在 PHP 匿名函數中看到 `use ($var)`,如: ```php= $message = 'hello'; // Inherit $message $example = function () use ($message) { var_dump($message); }; $example(); // string(5) "hello" ``` 但卻搞不清楚 `use ($var)` 是作什麼用的,原來,要在匿名函數中取用外部變數時,需要透過使用 `use ($var)` 語法。 ```php= $message = 'hello'; // No "use" $example = function () { var_dump($message); }; $example(); // Notice: Undefined variable: message in /example.php on line 6 // NULL ``` 若是沒使用 `use($var)`,匿名函數就無法取得 parent scpoe 的變數了 此外,`use` 變量的值來自定義函數時,而不是呼叫時: ```php= $message = "hello"; $f = function () use ($message) { echo $message; }; $message = "how are you?"; $f(); // hello ``` 當 use 中為傳址變數 (變數前加上 `&`): ```php= $message = "hello"; $f = function () use (&$message) { echo $message; }; $message = "how are you?"; $f(); // how are you? ``` 參考: * https://www.php.net/manual/en/functions.anonymous.php * https://stackoverflow.com/questions/1065188/in-php-what-is-a-closure-and-why-does-it-use-the-use-identifier ###### tags: `PHP`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up