php - 让 PHP 函数默认使用全局变量?

标签 php function variables

假设我有很多像下面这样的函数,并且会涉及一些变量。例如,我将使用时区...

function tell_time($values, $timezone = "Greenwich"){
     // Do something dealing with the timezone
}

function expected_arrival_time($values, $timezone = "Greenwich"){
     // Do something dealing with the timezone
}

function delayed_shipment_arrival($values, $timezone = "Greenwich"){
     // Do something dealing with the timezone
}
// ... and so on....

现在,如果服务器移动到不同的时区,所有这些都需要更新。什么是“正常”,比如单独更改所有默认值...

function tell_time($values, $timezone = "Mountain"){
     // Do something dealing with the timezone
}

function expected_arrival_time($values, $timezone = "Mountain"){
     // Do something dealing with the timezone
}

function delayed_shipment_arrival($values, $timezone = "Mountain"){
     // Do something dealing with the timezone
}
// ... and so on....

但是,如果我想让这个代码在开源设置中可访问,服务器时区可能会经常更改,具体取决于谁下载和安装,这对很多人来说可能会非常麻烦。但是,重新设计所有逻辑并不理想。什么是最简单的(假设我设置了服务器变量),就像...

function tell_time($values, $timezone = $_SERVER["timezone"]){
     // Do something dealing with the timezone
}

function expected_arrival_time($values, $timezone = $_SERVER["timezone"]){
     // Do something dealing with the timezone
}

function delayed_shipment_arrival($values, $timezone = $_SERVER["timezone"]){
     // Do something dealing with the timezone
}
// ... and so on....

然后,当有人下载​​并安装时,它只是从在安装时设置的服务器变量或其他潜在的全局变量中提取。或者可能从客户或其他方面的一些 session 数据中提取。关键是,我想要默认值,我可以在其中设置许多功能以共享相同的默认值,以便默认值易于更新。有没有好的方法来做到这一点?我不希望深入研究每一个函数,而不得不将其更改为设置默认值并使用单独的内部逻辑从变量中提取数据,因为这只会让后来的人忙于处理代码。

最佳答案

你可以使用 constant .在文件顶部定义它并让您的函数使用它。例如

define('CUSTOM_TIMEZONE', 'Mountain');

function tell_time($values, $timezone = CUSTOM_TIMEZONE) {
// Your code here
}

只需更改常量值,它就会随处更改。

关于php - 让 PHP 函数默认使用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66359109/

相关文章:

PHP 索引数组到关联 JSON

javascript - JS中如何判断一个字符串是否同时包含小写和大写字母?

c++ - 更改表条目没有重定向功能?

java - 关闭jframe并在java中重新打开后保存变量

javascript - 使用变量引用数组

php - 显示来自同一 mysql 列的两个单独值的问题

php - Mysql 注册事务

variables - 将批处理变量保存在文本文件中

php - 有点简单的PHP数组求交问题

Oracle:从 "select from dual"调用函数不执行任何操作