PHP和C的变量作用域区别:块作用域不完全一样?

2022-01-04 00:00:00 c scope php

以下PHP代码将输出3.

The following PHP code will output 3.

function main() {
    if (1) {
        $i = 3;
    }
    echo $i;
}

main();

但是下面的 C 代码会引发编译错误.

But the following C code will raise a compile error.

void main() {
    if (1) {
        int i = 3;
    }

    printf("%d", i);
}

PHP 中的变量不是严格块作用域的吗?PHP中定义在内部块中的变量可以在外部块中使用吗?

So variables in PHP are not strictly block-scoped? In PHP, variables defined in inner block can be used in outer block?

推荐答案

PHP 只有函数作用域 - if 等控制结构不会引入新的作用域.但是,如果您使用尚未声明的变量,它也不介意.$i 不会存在于 main() 之外,或者如果 if 语句失败,但您仍然可以自由地回显它.

PHP only has function scope - control structures such as if don't introduce a new scope. However, it also doesn't mind if you use variables you haven't declared. $i won't exist outside of main() or if the if statement fails, but you can still freely echo it.

如果您将 PHP 的 error_reporting 设置为包含通知,则如果您尝试使用尚未定义的变量,它将在 运行时 发出 E_NOTICE 错误.所以如果你有:

If you have PHP's error_reporting set to include notices, it will emit an E_NOTICE error at runtime if you try to use a variable which hasn't been defined. So if you had:

function main() {
 if (rand(0,1) == 0) {
  $i = 3;
 }
 echo $i;
}

代码会运行良好,但有些执行会回显 '3'(当 if 成功时),有些会引发 E_NOTICE 并且什么都不回显,如 $i 不会在 echo 语句的范围内定义.

The code would run fine, but some executions will echo '3' (when the if succeeds), and some will raise an E_NOTICE and echo nothing, as $i won't be defined in the scope of the echo statement.

在函数之外,$i 永远不会被定义(因为函数有不同的作用域).

Outside of the function, $i will never be defined (because the function has a different scope).

更多信息:http://php.net/manual/en/language.variables.scope.php

相关文章