Re: Global or include?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Jan 5, 2011 at 3:40 PM, Paul Halliday <paul.halliday@xxxxxxxxx>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

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux