问题描述
关于全局变量初始化,
function hello_testing() {
global $conditional_random;
if (isset($conditional_random)) {
echo "foo is inside";
}
}
在调用hello_testing()
函数之前,可能无法初始化全局变量(conditional_random).
The global variable (conditional_random) may not be initialized before the hello_testing()
function is called.
那么,当未初始化$conditional_random
时,通过isset()
进行的验证会如何?它会失败还是永远都是真的?
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 ;-)
调用hello_testing();
函数,而不设置变量:
Calling the hello_testing();
function, without setting the variable:
hello_testing();
我没有输出-表示返回了 isset
false
.
I get no output -- which indicates isset
returned false
.
设置变量后,调用函数:
Calling the function, after setting the variable:
$conditional_random = 'blah';
hello_testing();
我得到一个输出:
foo is inside
表明 global
可以正常工作,当变量设置为时-嗯,对此应该毫无疑问^^
但是请注意,如果设置了变量,则isset
将返回false
,并且null
!
But note that isset
will return false
if a variable is set, and null
!
请参见 isset()
的手册页
这意味着更好的测试是:
Which means that a better test would be:
function hello_testing() {
global $conditional_random;
var_dump($conditional_random);
}
hello_testing();
这将显示:
null
否注意:该变量存在!即使null
.
No Notice: the variable exists! Even if null
.
由于我没有在函数外部设置变量,因此它表明global
设置变量-但它没有输入值;这表示null
(如果尚未在函数外部设置).
As I didn't set the variable outside of the function, it shows that global
sets the variable -- but it doesn't put a value into it; which means it's null
if not already set outside the function.
时间:
function hello_testing() {
//global $conditional_random;
var_dump($conditional_random);
}
hello_testing();
赠予:
Notice: Undefined variable: conditional_random
证明已启用通知;-)
并且,如果global没有对变量进行"设置",那么前面的示例也会给出相同的提示.
And, if global didn't "set" the variable, the previous example would have given the same notice.
最后,
function hello_testing() {
global $conditional_random;
var_dump($conditional_random);
}
$conditional_random = 'glop';
hello_testing();
赠予:
string 'glop' (length=4)
(这纯粹是为了证明我的示例并未受骗^^)
这篇关于isset()和PHP全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!