Variable scope difference between PHP and C: block scope is not exactly the same?(PHP和C的变量作用域区别:块作用域不完全一样?)
问题描述
以下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
这篇关于PHP和C的变量作用域区别:块作用域不完全一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP和C的变量作用域区别:块作用域不完全一样?
基础教程推荐
- Web 服务器如何处理请求? 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- php中的foreach复选框POST 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- php中的PDF导出 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
