PHP变量可以在本地环境中读取,但不能在实时环境中读取


PHP Variable can be read in local enviroment, but not in live

我的笔记本电脑上运行着一台本地服务器,我在该服务器上测试我的网站,我注意到当我将当前网站上传到实时服务器时,部分服务器崩溃了。我发现这个错误是由一个类似的函数引起的

$other=1;
function example(){
$variable =1+$other;
return $variable;
}

但是,如果我将变量$other放入函数中,它就可以正常工作。显然,与现场服务器相比,本地服务器上有不同的设置,但是什么导致了这种情况?

您需要在函数中注入参数:

function example($other){
    $variable = 1 + $other;
    return $variable;
}
$other = 1;
example($other);

您可能想了解PHP中的作用域。

您应该定义类似function test()的函数,而不是函数($)