According to the most programming languages scope rules, I can access variables that defined outside of functions inside them, but why this code doesn't work?
<?php
$data = 'My data';
function menugen(){
echo "[".$data."]";
}
menugen();
?>
There is []
in output.
It is not working because you have to declare which global variables you'll be accessing:
otherwise you can access it as
$GLOBALS['data']
, see http://php.net/manual/en/language.variables.scope.phpEven if a little OT, I'd suggest you avoid using globals at all and prefer passing as parameters.
Another way to do it:
It's a matter of scope. In short, Global variables should be avoided SO:
You either need to pass it as a parameter:
OR have it in a class and access it
Edit: See @MatteoTassinari answer as well as you can mark it as global to access it but global vars are generally not required so it would be wise to re-think your coding.
If you want you can use "define" function but this function create a constants which can't be changed once defined.
http://www.w3schools.com/php/php_constants.asp
You can do one of the following:
Or
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).
You need to pass the variable into the function: