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 []
.
PHP The global Keyword The global keyword is used to access a global variable from within a function.
To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword.
That's because variables aren't really global in PHP. The scope of a typical PHP program is one HTTP request. Session variables actually have a wider scope than PHP "global" variables because they typically encompass many HTTP requests.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With