PHP 中未分配的静态变量包含什么以及为什么它在浏览器输出 window 中打印空白 space?

What does the unassigned static variable in PHP contain and why it prints blank space in a browser output window?

我有以下代码片段,请仔细查看:

<!DOCTYPE html>
<html>
  <body>

  <?php
    function myTest() {
      static $x;
      echo $x;
      $x++;
    }

    myTest();
    echo "<br>";
    myTest();
    echo "<br>";
    myTest();
   ?> 

  </body>
</html>

注意: 包含上述代码的文件的名称是 demo.php,它在我笔记本电脑上的位置是 C:\xampp\htdocs\php_playground\demo.php

当我 运行 通过点击 URL http://localhost/php_playground/demo.php 将上述程序输入我的浏览器时,我收到的输出如下:

1
2 

同样附上截图,请看一下。

  1. 我的问题是为什么输出中的第一行是空白包含 只有白色 space?
  2. 为什么它不打印 0 或类似单词 "NULL" 或 "Empty" 之类的东西?
  3. PHP中未分配的静态变量实际上包含什么?
  4. 静态未赋值变量的默认值和未赋值普通变量的默认值是否不同?

请给我合适的答案和适当的解释。

因为 NULL 什么都不是,它只是一个变量。你得到 2 个输出,因为你第一次调用它时,它被初始化为值:1,然后递增。

<?php
    function myTest() {
      static $x;
      echo $x;
      $x++;
    }

    myTest(); // INIT
    echo "<br>";
    myTest(); // 1
    echo "<br>";
    myTest(); // +1
   ?> 

如果您将 $x 声明为 0,那么它会打印 0。

静态变量(classes), (functions

PHP 中未分配的变量被转换为 NULL

<?php echo NULL; ?> 不回应任何东西,因为 NULL 没有价值。

来自 NULL page of the PHP documentation(强调我的):

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().

尝试在您的代码段中将 echo $x; 替换为 var_dump($x),它将输出以下内容:

NULL
int(1)
int(2)

Try it

因为第一步变量在"static"中赋值但不包含任何值;

一样
$t = null;
echo $t;

Why it's not printing 0 or something like the word "NULL" or "Empty" something like that?

因为 null 是 "nothing to see",变量已定义但没有任何值

What does actually an unassigned static variable in PHP contain? After you write this code

static $x;

您在全局内存中获得范围以将数据保存到其中。 我们知道这个变量 link 与当前 space 在内存中。

写完后

unset($x)

你在内存(数据)中清除这个space并删除link到这个space(变量)。

Does the default value of an static unassigned variable and the default value of unassigned normal variable differ?

是的,这是不同的。因为如果你不分配变量

echo $test;

you get error - Notice: Undefined variable:

因为你真的没有这个变量而且

之后
static $test;
echo $test;

现在你有了这个变量,你有 link 内存,但是在这个内存中你没有任何数据。