Lets say I have this:
function myFunc()
{
global $distinct_variable;
die ($distinct_variable);
}
function anotherFunc()
{
$distinct_variable = 'Hello World';
myFunc();
}
anotherFunc();
For anotherFunc() to correctly show ‘Hello World’, it must be written like this
{
global $distinct_variable;
$distinct_variable = 'Hello World';
myFunc();
}
Now it will show the message, but why must I global $distinct_variable; in anotherFunc() since it is a global in myFunc() which is within anotherFunc()
Yes, I know that variables inside functions won’t go outside of them, but I was thinking it should have worked…
Could someone explain why isn’t it working?
Thanks.
Thank you for your answers, I get it now 🙂
A
globalvariable is exactly that – it exists in the GLOBAL scope ONLY.Everything in PHP (except superglobals) exist in only one scope – be that the global scope, or the scope of a function/method. Scope does not cascade – so just because you have a variable in an “outer” function does not make it available to an “inner” function.
Similarly,
globalfetches the variables defined in the GLOBAL scope only (the top-most scope), not simply “the scope above this one, from which I was called”. This is what you tried to do, but it absolutely will not work. This level of finer-grained control is what function arguments/return values are for.