I’m not so advanced with PHP and am looking for the best solution to the following:
- I have a PHP array that holds important information about my script that
I need to RE-USE this frequently in my script.
$my_settings = array('width'=>'300', 'height'=>'200', ...);
-
I store that in a MySQL db.
-
The PHP script needs to get that array from MySQL once each time it runs in order to know how to compose the view.
(The array will eventually become quite large… Maybe few hundred rows…)
What is the best practice to get and define this array only ONCE in the beginning of my script, so I can re-use it all the time by other functions etc…?
Is it by defining it globally?
global $my_settings;
$my_settings = get_my_settings_from_db();
function returnSetting($key='') {
global $my_settings;
return $my_settings[$key];
}
Or is this bad idea?
What is the most efficient way to do it?
Thanks!
Instead of using
global(which is a bad thing to do) you should inject the variable (or even better the part you need into the function that needs it):Or perhaps better create a settings class:
Let’s say you have a class which needs some settings you could do the following:
When doing it this you will make you code better testable and maintainable.
Note this is just something I written with a beer in one hand and it is untested, but you should get the idea. 🙂