这适用于
<?php
error_reporting(E_ALL);
$a = null;
var_dump($a); // outputs no notice and NULL
这会产生通知吗?
<?php
error_reporting(E_ALL);
$a;
var_dump($a); // outputs a notice followed by NULL
这是
<?php
error_reporting(E_ALL);
class some_class
{
private $a;
public static $b;
public function __construct()
{
echo var_dump($this->a); // outputs NULL
}
}
var_dump(some_class::$b); // outputs NULL
new some_class();
请注意未来的读者
这个答案是基于最初的帖子,在介绍类的使用之前https://stackoverflow.com/revisions/36752382/1并且未标记为附加编辑。
"后跟NULL"
- 这是正常行为
来自变量基础手册http://php.net/manual/en/language.variables.basics.php
"没有必要在PHP中初始化变量,但这是一种非常好的做法。未初始化的变量根据使用它们的上下文有其类型的默认值-布尔值默认为FALSE,整数和浮点值默认为零,字符串(例如在echo中使用)设置为空字符串,数组变为空数组。"
示例#1未初始化变量的默认值
<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);
// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true'n" : "false'n");
- 注意
outputs NULL
,即使在未定义的变量上也是如此
"@mistermartin我想我本以为在声明$a时会发出通知;而不是在var_dump($a);?–MonkeyZeus"
这是因为你没有试图以任何方式、形状或形式访问它
简单地做:(作为一个有效的声明,我可以添加)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$a; // Awaits further instructions. Won't complain till then.
在介绍var_dump();
或任何其他可能使用它的有效函数之前,不会发出通知
- 把它想象成地面上的气体就在你的脚下。在你介绍一个点燃的火柴(或Zippo)之前,它真的不会有多大作用
另一个是没有var_dump()
的"echo"会抛出一个通知,但没有NULL。
即:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo $a; // This will make it complain, as will var_dump($a); in its place.
投掷:
注意:未定义的变量:第x行上的/path/to/file.php中的一个