gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:17:11 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com