Search code examples
phpsuperglobals

How to work with $GLOBALS


I have 2 different php files, and in one of the file I created a global array

$GLOBALS['system'] = array(
    'mysqli' => array(
        'host'      => 'localhost',
        'username'  => 'root',
        'password'  => '',
        'database'  => 'database'
    )
);

How can I be able to use this array in another file e.g.

$GLOBALS['system']['mysql']['host'];

Solution

  • $GLOBALS['system'] = array();
    

    This is unnecessary. Just do

    $system = array();
    

    Now, you can use $system anywhere you want (in other includes, etc), but the catch is that functions won't see it due to scope. That means that each function doesn't have access to $system because it's not in the global scope (and that's a good thing because what if you needed to use $system inside a function?) Now, you can always fall back to

    function foo() {
         echo $GLOBALS['system'];
    }
    

    But that's clunky and it relies on $system being defined somewhere and not changing. So let's inject it instead

    function foo($system) {
         echo $system;
    }
    foo($system);