Regarding global variable initialization,
function hello_testing() {
global $conditional_random;
if (isset($conditional_random)) {
echo "foo is inside";
}
}
The global variable (conditional_random) may not be initialized before the hello_testing() function is called.
So, what happens to my validation via isset() when $conditional_random is not initialized? Will it fail or it will always be true?
Well, why don’t you just test ? 😉
Note: It is not as easy as you’d think — read the full answer 😉
Calling the `hello_testing();` function, without setting the variable:
I get no output — which indicates
issetreturnedfalse.Calling the function, after setting the variable:
I get an output:
Which indicates
globalworks as expected, when the variable is set — well, one should not have any doubt about that ^^But note that
issetwill returnfalseif a variable is set, andnull!See the manual page of
isset()Which means that a better test would be:
And this displays:
No Notice: the variable exists! Even if
null.As I didn’t set the variable outside of the function, it shows that
globalsets the variable — but it doesn’t put a value into it; which means it’snullif not already set outside the function.While:
Gives:
It proves that notices are enabled 😉
And, if global didn’t "set" the variable, the previous example would have given the same notice.
And, finally:
Gives:
(This is to purely to demonstrate my example is not tricked ^^)