isset()和PHP全局变量

jus*_*joe 8 php variables function global-variables

我有一个关于全局变量初始化的问题.

function hello_testing() {
  global $conditional_random;
  if (isset($conditional_random)) {
      echo "foo is inside";  
  }
}
Run Code Online (Sandbox Code Playgroud)

hello_testing()调用函数之前,可能不会初始化全局变量(conditional_random).

那么,我的验证通过isset()何时$conditional_random未初始化会发生什么?它会失败还是永远都是真的?

Pas*_*TIN 13

好吧,你为什么不试试?;-)

注意:不像你想象的那么容易 - 阅读完整的答案;-)


调用该hello_testing();函数,而不设置变量:

hello_testing();
Run Code Online (Sandbox Code Playgroud)

我没有输出 - 表示isset返回false.


设置变量后调用该函数:

$conditional_random = 'blah';
hello_testing();
Run Code Online (Sandbox Code Playgroud)

我得到一个输出:

foo is inside
Run Code Online (Sandbox Code Playgroud)

global当设置变量时,这表示按预期工作- 嗯,人们不应该对该^^有任何疑问



但请注意,如果设置了变量,isset它将返回false,并且null!
参见手册页isset()

这意味着更好的测试将是:

function hello_testing() {
  global $conditional_random;
  var_dump($conditional_random);
}

hello_testing();
Run Code Online (Sandbox Code Playgroud)

这显示:

null
Run Code Online (Sandbox Code Playgroud)

没有通知:变量存在!即使null.

由于我没有在函数外部设置变量,因此它显示global 设置变量 - 但它没有为其赋值; 这意味着null如果还没有设置在功能之外.


同时:

function hello_testing() {
  //global $conditional_random;
  var_dump($conditional_random);
}

hello_testing();
Run Code Online (Sandbox Code Playgroud)

给:

Notice: Undefined variable: conditional_random
Run Code Online (Sandbox Code Playgroud)

证明通知已启用;-)

而且,如果全局没有" 设置 "变量,前面的例子会给出相同的通知.


最后:

function hello_testing() {
  global $conditional_random;
  var_dump($conditional_random);
}

$conditional_random = 'glop';
hello_testing();
Run Code Online (Sandbox Code Playgroud)

给:

string 'glop' (length=4)
Run Code Online (Sandbox Code Playgroud)

(纯粹是为了证明我的例子不被欺骗^^)

  • 那么您的“测试”是看看是否触发了通知?虽然 isset 如何工作的解释很好,但这似乎并没有提供有用的替代方案。 (2认同)

Omn*_*Omn 8

您可以通过检查$ GLOBALS中是否存在密钥来检查是否已创建全局:

echo array_key_exists('fooBar', $GLOBALS)?"true\n":"false\n";
//Outputs false

global $fooBar;

echo array_key_exists('fooBar', $GLOBALS)?"true\n":"false\n";
//Outputs true

echo isset($fooBar)?"true\n":"false\n";
//Outputs false
Run Code Online (Sandbox Code Playgroud)

这是我知道检查全局存在而不触发警告的唯一方法.

正如Manos Dilaverakis所提到的,你应该尽可能避免使用全局变量.