Php 将变量设置为空
这个很好用Php 将变量设置为空,php,variables,null,Php,Variables,Null,这个很好用 <?php error_reporting(E_ALL); $a = null; var_dump($a); // outputs no notice and NULL 未来读者注意 这个答案基于最初的帖子,在引入类的使用之前,没有标记为附加编辑 “后跟NULL” 这是正常的行为 来自变量基础手册 “在PHP中不必初始化变量,但这是一种很好的做法。未初始化的变量有其类型的默认值,具体取决于使用它们的上下文-布尔值默认为FALSE,整数和浮点值默认为零,字符串(例如,在e
<?php
error_reporting(E_ALL);
$a = null;
var_dump($a); // outputs no notice and NULL
未来读者注意
这个答案基于最初的帖子,在引入类的使用之前,没有标记为附加编辑
“后跟NULL”
- 这是正常的行为
来自变量基础手册
“在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");
在您引入var_dump()之前不会发布通知
或可能使用它的任何其他有效函数
- 把它想象成地面上的气体就在你脚边。在你引入点燃火柴(或Zippo)之前,它实际上不会有多大用处
另一个是不带var\u dump()
的“echo”将抛出通知,但不带NULL
即:
你的问题是什么<代码>$a代码>不是有效的赋值。在第二个示例中,您没有将$a
设置为null
,但当您尝试访问未定义的变量时,它是默认显示。@mistermartin我想我会在声明$a代码>而不是在var\u dump($a)尝试访问它时代码>?@MonkeyZeus我对我之前发布的答案做了一些编辑,概述了发生的事情,不确定你是否看到了它们(编辑)。我希望它能对这个问题有所启发;-)(参见代码中的注释)。@Fred ii-谢谢你的详细回答。我想我的问题是我理解这个行为,但我不理解独立$a代码>不生成通知。请看我的更新。这是否意味着PHP在编译时将未分配的类属性初始化为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();
<?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");
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$a; // Awaits further instructions. Won't complain till then.
<?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.