Re: Global or include?
| From: | Nathan Nobbe | Date: | Wed, 05 Jan 2011 23:35:48 +0000 |
| Subject: | Re: Global or include? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-310517@lists.php.net to get a copy of this message | ||
On Wed, Jan 5, 2011 at 4:27 PM, Nathan Nobbe <quickshiftin@gmail.com> wrote:
> On Wed, Jan 5, 2011 at 3:40 PM, Paul Halliday <paul.halliday@gmail.com>wrote:
>
>> Say you have 10 or so scripts and a single config file. If you have
>> main.php, functions1.php, functions2.php, functions3.php..
>>
>> Does is hurt to do an include of the config file in each separate
>> script, even if you only need a few things from it, or should you
>> just specify what you want with a 'global' within each
>> script/function?
>>
>
> touching on what Nicholas said this could be handled in OOP via the
> singleton pattern, however there are ways of dealing w/ it in global
> function land as well.
>
> i see 4 immediate options
> . load config from each file (performance hit mitigated if config is a php
> array and using opcode caching)
> . global variable
> . session storage
> . config fetching function w/ static variable
>
> the last option is the one i'd like to describe since i think its the
> cleanest, even if you have opcode caching enabled. the function would look
> something like this
>
> function load_config()
> {
> static $cachedConfig = null;
>
> if($cachedConfig !== null)
> {
> // load file and store value(s) in $cachedConfig
> }
>
> return $cachedConfig;
> }
>
> now all you have to do is make load_config() available in all your files,
> via something like require_once on the file which defines load_config().
> the result is the configuration will only be read once on a given page
> load, thereafter its contents will come from memory.
>
> this is actually very similar to the singleton approach in OOP.
>
> -nathan
>
UMM, check that, the conditional should read
if($cachedConfig === null)
{
// load config file :)
$cachedConfig = $someValue; // ...
}
my bad, lol!
-nathan