在 PHP 中,您必须使用 global
关键字以便在函数内部时从全局范围访问变量。但是,您如何访问
父函数范围内的变量?
在示例中:
function foo() {
$content = 'foobar';
function bar() {
echo $content; // echos nothing
}
}
如何访问 $content
变量?
最佳答案
您有两个选择:
将
$content
作为参数function foo() { $content = 'foobar'; function bar($content) { echo $content . '1'; // 'foobar1' } bar(); } foo();
使用闭包 ( PHP Manual ) (PHP 5.3.0+)
请注意,与声明函数的“传统方式”相比,函数声明有点不同。
function foo() { $content = 'foobar'; $bar = function() use ($content) { echo $content . '1'; }; // <-- As it's an assignment, end with a ';' $bar(); } foo(); // 'foobar1'
关于php - 从嵌套函数内部的函数访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282256/