从函数内部调用函数,变量作用域
我只是想确认以下内容不起作用:
function f1(){
$test = 'hello';
f2();
}
function f2(){
global $test;
echo $test;
}
f1(); //expected result 'hello'
http://php.net /manual/en/language.variables.scope.php
有没有办法像在 Javascript 中那样在作用域链中“流动”?从手册来看,我的选择似乎是全局的或根本没有。
我只是想知道这是否正确。
I just want to confirm that the following will NOT work:
function f1(){
$test = 'hello';
f2();
}
function f2(){
global $test;
echo $test;
}
f1(); //expected result 'hello'
http://php.net/manual/en/language.variables.scope.php
Is there no way to just "flow" up the scope chain like you can do in Javascript? From the manual, it seems that my option for this is global or nothing at all.
I just wanted to know if that was correct.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不会工作。
您可以将变量作为参数传递:
It won't work.
You can pass the variable as a parameter though :
在 f1 中添加
global $test;
Add
global $test;
in f1global
指令使本地函数成为顶级全局作用域的一部分。它不会迭代备份函数调用堆栈来查找该名称的变量,它只是跳回绝对顶层,因此如果您完成了:基本上,请考虑
global
相当于:The
global
directive makes a local function part of the top-level global scope. It won't iterate back up the function call stack to find a variable of that name, it just hops right back up to the absolute top level, so if you'd done:Basically, consider
global
to be the equivalent of: