奇怪的空问题
我想使用这样的代码:
$arr=array('a'=>$a);
但是 $a
没有定义,所以我收到错误。但是如果我在
if (!isset($a))
$a=null;
所有工作之前编写这段代码。为什么?一开始$a
没有定义,所以$a=null
。或underfined!=NULL
?
I want to use such code:
$arr=array('a'=>$a);
but $a
is not defined, so I get error. But if I write this code before
if (!isset($a))
$a=null;
all works. Why? In the beginning $a
is not defined , so $a=null
. or underfined!=NULL
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您编写时,
这意味着您希望键“a”引用名为 $a 的变量引用,该变量引用最初并不存在,因此您会收到错误;但是当你事先添加时
,虽然你将 $a 设置为 null 但实际上你正在创建一个 PHP 已知的名为 $a 的变量引用,因此不会有错误。
When you write
it means that you want the key "a" refers to a variable reference named $a which does not exist in the first place thus you are getting an error; but when you add
before hand, although you are setting $a to null but actually you are creating a variable reference named $a that's known by PHP so there will be no errors.
是的,事实上
undefined
!=null
,尽管区别仅在于 PHP 在决定是否抛出错误时的视角。否则都是一样的。Yes, in truth
undefined
!=null
, although the difference is only in the eyes of PHP when it decides whether to throw an error or not. Otherwise it's the same thing.正如您已经发现的,undefined 与 null 不同。
未定义意味着名称 $a 尚未进入您的函数/代码的范围。
$a=null
是分配给变量的(无)值。顺便说一句,您应该收到一条通知,而不是错误,因为使用未定义的变量作为右值,php 会警告您可能存在拼写错误并继续执行脚本。
根据经验,如果您在赋值 (=) simbol(左值名称)左侧寻址未定义的变量,则 php 会创建一个新变量名称并将其绑定到当前范围(如果引用位于对(您是否使用包含的值而不是变量本身)php 会警告您并继续。您可以通过 error_reporting 函数更改此行为。
As you already discovered undefined is different from null.
Undefined means that the name $a in not yet into the scope of your function/code.
$a=null
is a (no)value assigned to a variable.By the way you should get a Notice, not an error as using undefined variables as right-values php warns you about a probable typo and proceed with the script execution.
As a rule of thumb, if you address an undefined variable on the left of the assignment (=) simbol (a left-value name) then php create a new variables name and bind it into the current scope, if the reference is on the right (are you using the value contained instead than the variable itself) php warns you and keep going. You can change this behaviour by the error_reporting function.
请参阅 isset 手册
see the manual of isset