Let's say I have a lot of functions like the following, and will be making more involving some variable. For example, I'll use timezone...
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....
Now, if the server moves to a different timezone, all of those need to be updated. What would be 'normal' would be something like individually changing all the defaults...
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....
However, if I'm wanting to make this code accessible in an open source setting, where the server timezone may change frequently depends on who downloads and installs, this may get very cumbersome for many people real fast. However, reworking all the logic isn't ideal. What would be simplest (assuming I have the server variable set), would be something like...
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....
Then, when someone downloads and installs, it just pulls from a server variable that gets set at install time, or potentially some other global variable. Or maybe pulling from some session data for customer or something else even. The point is, I want default where I can set many functions to share the same default, so that default is easy to update. Is there a good way to do this? I'd prefer not going into every single function and having to change it to setting defaults and pulling from variables with separate internal logic, as it just makes the code filled with busywork for any who come later.
You could use a constant. Define it at the top of a file and let your functions use that. E.g.
define('CUSTOM_TIMEZONE', 'Mountain');
function tell_time($values, $timezone = CUSTOM_TIMEZONE) {
// Your code here
}
Just change the constants value and it's changed everywhere.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments