在匿名 PHP 函式中從父級作用域訪問變數
“use” 關鍵字可用於將變數繫結到特定函式作用域內。
使用 use 關鍵字將變數繫結到函式作用域內 -
示例
<?php $message = 'hello there'; $example = function () { var_dump($message); }; $example(); $example = function () use ($message) { // Inherit $message var_dump($message); }; $example(); // Inherited variable's value is from when the function is defined, not when called $message = 'Inherited value'; $example(); $message = 'reset to hello'; //message is reset $example = function () use (&$message) { // Inherit by-reference var_dump($message); }; $example(); // The changed value in the parent scope // is reflected inside the function call $message = 'change reflected in parent scope'; $example(); $example("hello message"); ?>
輸出
這將產生以下輸出:-
NULL string(11) "hello there" string(11) "hello there" string(14) "reset to hello" string(32) "change reflected in parent scope" string(32) "change reflected in parent scope"
最初,首先呼叫“example”函式。第二次呼叫時,$ message 被繼承,其值在函式被定義時發生改變。$ message 的值被重置並再次繼承。由於值在根/父級作用域中被改變,因此當函式被呼叫時這些改變會被反映出來。
廣告