为什么解释器显示未定义为NULL?

发布于 2024-12-19 10:53:58 字数 687 浏览 6 评论 0原文

上次我对 PHP 进行了很多探索,我很好奇是否可以像 C++ 那样定义变量而无需初始化它。

如果我运行此代码,那么解释器不会输出致命错误(仅通知变量 test 未定义):

<?php 

$test = (int) $test;

?>

如果我尝试使用 var_dump() 函数检查它,我得到:

int(0)

我假设解释器自动将 undefined 转换为整数。嗯,好吧,这很聪明。 但是当我删除负责类型转换的代码并使用 var_dump() 函数检查它时,我得到:

NULL

好吧,好吧。因此,当我将未定义变量分配为未定义变量时,我得到的变量为 NULL。我可以理解口译员在奔跑时为我做这件事。但是当我尝试这样的事情时:

<?php

var_dump($test);
var_dump($test);

?>

我收到两个通知,测试未定义,但 var_dump() 返回 NULL,而不是未定义。现在我不明白了。如果我关闭通知,var_dump() 函数将与未定义的变量和分配给 NULL 的变量产生相同的结果。这是一个来自主题的问题。为什么解释器(或者更确切地说是 var_dump() 函数)将 undefined 和 NULL 视为相同?

Last time I'm exploring PHP pretty much and I was curious if it's possible to define variable without initializing it like in C++.

Well interpreter doesn't output an fatal eror (only a notice that variable test is undefined) if I'll run this code:

<?php 

$test = (int) $test;

?>

And if I try to check it with var_dump() function i get:

int(0)

I assumed interpreter automatically cast undefined to integer. Well, ok it's pretty clever.
But when I removed code repsonsible for type casting and checked it with var_dump() function I get:

NULL

Well, ok. So when I assign undefined variable as undefined variable I get variable with NULL. I can understand interpreter do it for me on the run. But when I try something like this:

<?php

var_dump($test);
var_dump($test);

?>

I get two notices that test is not defined, but var_dump() returns NULL, not undefined. And now I don't get it. If I'll turn off notices var_dump() function will have same result with undefined variables and variables assigned to NULL. And here comes a question from topic. Why interpreter (or rather a var_dump() function) treats undefined and NULL as same ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

写下不归期 2024-12-26 10:53:58

特殊的NULL值表示没有值的变量。 NULL 是 NULL 类型唯一可能的值。

如果满足以下条件,变量将被视为 null:
它已被分配常量 NULL。
尚未设置任何值
它已被取消设置()。

(int)$test = 强制转换,将值强制转换为数据类型(整数)

警告通知 = $test 引起的原因从未定义,并且您尝试使用它

var_dump($test) = 我不知道$test 的值,所以,我返回一个 null (通过 PHP)

The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.

A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().

(int)$test = casting, force a value to data type (integer)

warning notices = cause by $test is never defined, and you trying to use it

var_dump($test) = I dun have a value for $test, so, I return you a null (by PHP)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文