Php从外部函数获取全局变量的值

问题描述 投票:1回答:2

我在php中具有此测试功能

funtion drop()
{

    global $test_end;

    if(file_exists("test.php"))
    {
        $ddr="ok";
    }

    $test_end="ready";

}

我知道是否放了[[drop()),但我想知道的只是定义的例子,我的问题是关于如何在函数内部定义全局var的方式从此全局var内部函数中取出值,但在该函数最终执行时在此函数外部。

例如,放置drop(),然后运行echo $ test_end;外部功能并显示价值;

drop(); echo $test_end;

这是我的问题,该如何获得,感谢高级的帮助
php function global
2个回答
0
投票
全局变量不是一个坏的设计模式。但是拥有很多全局变量通常是编程不好的标志。您应该尝试将其最小化。

要检索值,您只需引用它:

function set() { global $test_end; $test_end="ready"; } function show() { global $test_end; print "in show() value=$test_end\n"; } function noscope() { print "in noscope() value=$test_end\n"; } $test_end="begin"; print "In global scope value=$test_end\n"; show(); noscope(); set(); print "after calling set()\n"; print "In global scope value=$test_end\n"; show(); noscope();


-1
投票
请勿使用全局变量,这是一个糟糕的设计,因为它会使您的代码混乱且难以阅读。有更好的选择。

给出您的简单示例,您只需从方法中返回值:

function drop() { if(file_exists("test.php")) { $ddr="ok"; } $test_end="ready"; return $test_end; } $test_end = drop();

如果情况更复杂,由于某种原因无法返回该值,请在变量前加&作为参考传递变量:

funtion drop(&$test_end) { if(file_exists("test.php")) { $ddr="ok"; } $test_end="ready"; } $test_end = null; drop($test_end); echo $test_end; // will now output "ready"

通过引用传递也不是一个很好的模式,因为它仍然会使您的代码混乱。

有关全局变量为何无效的更多信息

问题是,如果我正在查看您的代码,而我看到的只是这个:

drop(); echo $test_end;

我不知道$ test_end是如何设置的或它的值是什么。现在,假设您有多个方法调用:

drop(); foo(); bar(); echo $test_end;

我现在必须查看所有这些方法的定义,以找出$ test_end的值是什么。在较大的代码库中,这成为一个很大的问题。
© www.soinside.com 2019 - 2024. All rights reserved.