加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP中未初始化的变量

发布时间:2020-12-13 16:08:33 所属栏目: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
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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读