首页 > 解决方案 > php获取全局var外部函数的值

问题描述

我在 php 中有这个测试函数:

funtion drop() {
    global $test_end;

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

    $test_end="ready";
}

我知道如果我称它为drop()“ok”,例如。

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

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

drop();
echo $test_end;

标签: phpfunctionglobal

解决方案


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

给定您的简单示例,您可以从方法中返回值:

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


推荐阅读