Access a global variable in a PHP function

Amin Gholibeigian picture Amin Gholibeigian · Mar 28, 2013 · Viewed 124.4k times · Source

According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn't this code work?

<?php
    $data = 'My data';

    function menugen() {
        echo "[" . $data . "]";
    }

    menugen();
?>

The output is [].

Answer

Matteo Tassinari picture Matteo Tassinari · Mar 28, 2013

It is not working because you have to declare which global variables you'll be accessing:

$data = 'My data';

function menugen() {
    global $data; // <-- Add this line

    echo "[" . $data . "]";
}

menugen();

Otherwise you can access it as $GLOBALS['data']. See Variable scope.

Even if a little off-topic, I'd suggest you avoid using globals at all and prefer passing as parameters.