wonton
wonton

Reputation: 8247

PHP Including a config file multiple times

I have a config.php file that creates an array, something like

$config = array(
       'foo' => 'bar'
);
function foo()
{
       echo 'good';
}

I also have another utility.php file that prints stuff, that depends on config.php

require_once(-the absolute path to config.php-);
class Utility{
  function bar()
  {
    echo count($config);
    echo foo();
  }
}

I am in a situation where my index.php script depends on config.php as well as utility.php. Therefore, when I include foo.php I am including config.php again. Something like

require_once(-the absolute path to config.php-);
require_once(-the absolute path to utility.php-);
echo count($config);
utility::bar();

This function prints out

1good

However, when I attempt to call Utility::bar, it prints 0 for count($config) - the $config array never gets created in utility.php, in spite of count($config) returning 1 in index.php. Interestingly, calling function foo() in utility.php still returns "good". Making $config global didn't change anything (and I hear is bad style).

Upvotes: 0

Views: 395

Answers (1)

colonelclick
colonelclick

Reputation: 2215

It looks like you have a variable scope issue. Read about PHP variable scope. As an example I think if you changed

echo count($config);

to

global $config;
echo count($config);

it would work.

Upvotes: 1

Related Questions