如何从父函数的范围访问变量?

发布于 2024-12-19 14:00:54 字数 341 浏览 0 评论 0原文

我希望我的函数能够访问外部变量——特别是从其父函数。但是,使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

镜花水月 2024-12-26 14:00:54

仅为了举例,如果我理解您要做什么,您可以使用 闭包 (PHP 5.3+),因为使用 use 关键字“闭包也可以从父作用域继承变量”。

$a = "Level 1";

function first() {
    $a = "Level 2";

    $func = function () use ($a) {
        echo $a.'<br />';
    };

    $func();
}

first();
// prints 'Level 2<br />'

闭包最常用于回调函数。然而,这可能不是最好的使用场景。正如其他人所建议的,仅仅因为你可以做某事并不意味着它是最好的主意。

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.

$a = "Level 1";

function first() {
    $a = "Level 2";

    $func = function () use ($a) {
        echo $a.'<br />';
    };

    $func();
}

first();
// prints 'Level 2<br />'

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.

瑾夏年华 2024-12-26 14:00:54

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 call first again, PHP will again encounter a function declaration for second and crash, since the function second 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文