PHP中未初始化的变量

The PHP manual says

It is not necessary to initialize variables in PHP however it is a
very good practice. Uninitialized variables have a default value of
their type depending on the context in which they are used – booleans
default to FALSE, integers and floats default to zero, strings (e.g.
used in echo) are set as an empty string and arrays become to an empty
array.

我正在玩未经初始化的高尔夫变量,但该计划没有达到我的预期.经过检查,我注意到这种奇怪的行为(所有使用的变量都是未初始化的):

php > $a = $a + 1;
PHP Notice:  Undefined variable: a in php shell code on line 1
php > $b = $b - 1;
PHP Notice:  Undefined variable: b in php shell code on line 1
php > $c++;
PHP Notice:  Undefined variable: c in php shell code on line 1
php > $d--;
PHP Notice:  Undefined variable: d in php shell code on line 1
php > var_dump($a);
int(1)
php > var_dump($b);
int(-1)
php > var_dump($c);
int(1)
php > var_dump($d);
NULL

  1, – 1,按照手册中的说明进行操作.但是, – 没有.

之后,$a,$b和$c可用于计数.但是$d–;,不会改变$d的值,因为$d是NULL.

为什么$d设置为NULL,而不是-1?

使用前缀运算符产生相同的结果,顺便说一下:对于$v,变量设置为1;但对于 – $v;为NULL

最佳答案 从
manual

Note: …Decrementing NULL values has no effect too, but incrementing them results in 1.

因此,unitialized变量获得NULL值.递增此值得到1(为NULL 1).但是,如文档中所述,尝试递减没有效果.

此外,相关主题还有一个非常的good explanation.

这似乎违反直觉,但它是该语言的打字模型的结果.因此,为了避免这种行为,请始终遵循良好实践:始终初始化变量并注意非数值的算术运算.

点赞