PHP和C之间的可变范围不同:块范围不完全一样? [英] Variable scope difference between PHP and C: block scope is not exactly the same?

查看:103
本文介绍了PHP和C之间的可变范围不同:块范围不完全一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下PHP code将输出 3

The following PHP code will output 3.

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

main();

但下面的C code将引发编译错误。

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只有功能范围 - 控制结构,如如果不引入一个新的作用域。不过,这也不会,如果你使用没有声明的变量介意。 $ 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 错误的在运行时,如果您尝试使用的不是招一个变量的T被定义。所以,如果你有:

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;
}

在code会运行良好,但一些执行将呼应3(即如果成功时),有的会引发 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).

有关更多的信息:<一href=\"http://php.net/manual/en/language.variables.scope.php\">http://php.net/manual/en/language.variables.scope.php

这篇关于PHP和C之间的可变范围不同:块范围不完全一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆