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

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

我在php中具有此测试功能:

funtion drop() {
    global $test_end;

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

    $test_end="ready";
}

例如,如果我叫drop(),它会给我“确定”。

我的问题是:如果我在函数内部定义了全局变量,执行时如何在函数内部以及函数外部输出该变量的值?

例如,调用drop(),然后在函数外部运行echo $test_end;以获取值:

drop();
echo $test_end;
php function global
2个回答
2
投票

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

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

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的值是什么。在较大的代码库中,这成为一个很大的问题。


-1
投票

全局变量不是一个坏的设计模式。但是拥有很多全局变量通常是编程不好的标志。您应该尝试将其最小化。

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

 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();
© www.soinside.com 2019 - 2024. All rights reserved.