我在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;
答案 0 :(得分:3)
不要使用全局变量,这是一个糟糕的设计,因为它会使您的代码混乱且难以阅读。有更好的选择。
给出一个简单的示例,您可以从方法中返回值:
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 :(得分:-3)
全局变量不是一个坏的设计模式。但是,拥有大量的全局变量通常是不良编程的标志。您应该尽量减少它们。
要检索值,只需引用它即可:
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();