在匿名 PHP 函数中从父作用域访问变量
phpserver side programmingprogramming更新于 2025/9/2 0:12:00
可以使用 ‘use’ 关键字将变量绑定到特定函数的作用域中。
使用 use 关键字将变量绑定到函数的作用域 −
示例
<?php
$message = 'hello there';
$example = function () {
var_dump($message);
};
$example();
$example = function () use ($message) { // 继承 $message
var_dump($message);
};
$example();
// 继承变量的值来自函数定义时的值,而不是调用时的值
$message = '继承值';
$example();
$message = '重置为 hello'; //消息已重置
$example = function () use (&$message) { // 通过引用继承
var_dump($message);
};
$example();
// 父作用域中更改的值
// 反映在函数调用中
$message = '更改反映在父作用域中';
$example();
$example("hello message");
?>
输出
将产生以下输出 −
NULL string(11) "hello there" string(11) "hello there" string(14) "reset to hello" string(32) "changereflective in parent scope" string(32) "changereflective in parent scope"
最初,‘example’函数被第一次调用。第二次,$message 被继承,其值在函数定义时发生更改。$message 的值被重置并再次继承。由于该值在根/父作用域中发生更改,因此在调用函数时会反映更改。

