Access a global variable in a PHP function
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.
You can do one of the following:
<?php $data = 'My data'; function menugen() { global $data; echo "[" . $data . "]"; } menugen();
Or
<?php $data = 'My data'; function menugen() { echo "[" . $GLOBALS['data'] . "]"; } menugen();
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).
Another way to do it:
<?php$data = 'My data';$menugen = function() use ($data) { echo "[".$data."]";};$menugen();
UPDATE 2020-01-13: requested by Peter Mortensen
As of PHP 5.3.0 we have anonymous functions support that can create closures. A closure can access the variable which is created outside of its scope.
In the example, the closure is able to access $data
because it was declared in the use
clause.