Access a global variable in a PHP function

To address the question as asked, it is not working because you need to declare which global variables you’ll be accessing in the function itself:

$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 would suggest you avoid using globals at all and prefer passing data as parameters.

In this case, the above code look like this:

$data="My data";

function menugen($data) { // <-- Declare the parameter
    echo "[" . $data . "]";
}

menugen($data); // <-- And pass it at call time

Leave a Comment