有时我需要使用一个动态的值,这个值会因为代码是在测试环境还是在远程主机上执行而有所不同。
为了解决这个问题,我一直在使用以下功能:
function localhost($local_host_value, $remote_host_value = "")
{
if($_SERVER["REMOTE_ADDR"] == "127.0.0.1")
{
return $local_host_value;
}
else
{
return $remote_host_value;
}
}
你可以为上面引用的函数建议一种更优雅的方法或至少更好的名称吗?
答案 0 :(得分:1)
如果您不喜欢使用超全局变量
,可以尝试getenv('REMOTE_ADDR');
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');
// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
功能名称
function is_localhost(...) <-- more like determine is local host (boolean)
function get_host_value(...) <-- (string)
答案 1 :(得分:1)
function localhost($local_host_value, $remote_host_value = '') {
return $_SERVER['REMOTE_ADDR'] == '127.0.0.1'? $local_host_value : $remote_host_value;
}
在我看来更简洁干净,但也是如此。 或者使用getenv作为ajreal建议:
function localhost($local_host_value, $remote_host_value = '') {
return getenv('REMOTE_ADDR') == '127.0.0.1'? $local_host_value : $remote_host_value;
}
关于功能名称,get_host_value(...)
可能是我的选择
PS:当您的字符串不包含变量时,尝试使用单引号而不是双引号:Is there a performance benefit single quote vs double quote in php?
答案 2 :(得分:1)
我认为这种方法从长远来看并不是最佳的,因为所有设置都分布在整个代码中,而且很难实现。添加第三个服务器环境(例如,实时登台服务器)。
我会考虑使用某种中央配置,在一个点上加载所有配置值,具体取决于它运行的服务器。
相关: