It's a matter of scope. In short, global variables should be avoided so:
You either need to pass it as a parameter:
$data = 'My data';
function menugen($data)
{
echo $data;
}
Or have it in a class and access it
class MyClass
{
private $data = "";
function menugen()
{
echo this->data;
}
}
See @MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.
That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).
I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.
I was looking for this answer, sort of, I wanted to see if anyone else had something similar with respect to how $prefix would be passed to an anonymous function. Seems the global scope is the the way? This is my solution for prefixing an array in a non-destructive manner.
The proper way for accessing a global variable inside a function is answered above!
BUT if you do not want to use the global keyword, nor the $GLOBALS variable for some reason (for example you have multiple functions and you are "tired" of writing global $variable; every time), here is a workaround:
$variable = 42; // the global variable you want to access
// write a function which returns it
function getvar(){
global $variable;
return $variable;
}
//--------------
function func1()
{
// use that getter function to get the global variable
echo getvar(); // 42
}
function func2()
{
echo getvar(); // 42
}
...