如何从父函数的范围访问变量?
我希望我的函数能够访问外部变量——特别是从其父函数。但是,使用 global
关键字设置的范围太宽;我需要限制它。如何让这段代码输出“Level 2”而不是“Level 1”?我必须上课吗?
<?php
$a = "Level 1";
function first() {
$a = "Level 2";
function second() {
global $a;
echo $a.'<br />';
}
second();
}
first();
//outputs 'Level 1'
?>
I want my function to access an outside variable—from its parent function specifically. However, using the global
keyword sets too broad a scope; I need to limit it. How do I get this code to spit out 'Level 2' instead of 'Level 1'? Do I have to make a class?
<?php
$a = "Level 1";
function first() {
$a = "Level 2";
function second() {
global $a;
echo $a.'<br />';
}
second();
}
first();
//outputs 'Level 1'
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅为了举例,如果我理解您要做什么,您可以使用 闭包 (PHP 5.3+),因为使用
use
关键字“闭包也可以从父作用域继承变量”。闭包最常用于回调函数。然而,这可能不是最好的使用场景。正如其他人所建议的,仅仅因为你可以做某事并不意味着它是最好的主意。
Just for the sake of example, if I understand what you're trying to do, you could use a closure (PHP 5.3+), as "Closures may also inherit variables from the parent scope" with the
use
keyword.Closures are most commonly used for callback functions. This may not be the best scenario to use one, however. As others have suggested, just because you can do something doesn't mean it's the best idea.
PHP 没有嵌套函数或作用域的概念,嵌套函数是很糟糕的做法。所发生的情况是,PHP 只是遇到一个函数声明并创建一个普通函数
second
。如果您尝试再次调用first
,PHP 将再次遇到second
的函数声明并崩溃,因为函数second
已经声明。因此,不要在函数内声明函数。至于传递值,要么显式地将它们作为函数参数传递,要么如您所说,创建一个类如果有意义。
PHP has no concept of nested functions or scopes and it's terrible practice to nest functions. What happens is that PHP simply encounters a function declaration and creates a normal function
second
. If you try to callfirst
again, PHP will again encounter a function declaration forsecond
and crash, since the functionsecond
is already declared. Therefore, don't declare functions within functions.As for passing values, either explicitly pass them as function parameters or, as you say, make a class if that makes sense.