The following PHP code will output 3
.
以下PHP代码将输出3。
function main() {
if (1) {
$i = 3;
}
echo $i;
}
main();
But the following C code will raise a compile error.
但是下面的C代码会引发编译错误。
void main() {
if (1) {
int i = 3;
}
printf("%d", i);
}
So variables in PHP are not strictly block-scoped? In PHP, variables defined in inner block can be used in outer block?
那么PHP中的变量不是严格的块范围的?在PHP中,内部块中定义的变量可以用在外部块中吗?
1 个解决方案
#1
49
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只有函数作用域 - 控制结构,如果不引入新的作用域。但是,如果您使用未声明的变量,它也不介意。 $ i不会存在于main()之外,或者如果if语句失败,但你仍然可以*地回应它。
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:
如果将PHP的error_reporting设置为包含通知,则在尝试使用尚未定义的变量时,它将在运行时发出E_NOTICE错误。所以如果你有:
function main() {
if (rand(0,1) == 0) {
$i = 3;
}
echo $i;
}
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.
代码运行正常,但是一些执行将回显'3'(当if成功时),并且一些将引发E_NOTICE并且什么都不回显,因为$ i将不在echo语句的范围内定义。
Outside of the function, $i
will never be defined (because the function has a different scope).
在函数之外,永远不会定义$ i(因为函数具有不同的范围)。
For more info: http://php.net/manual/en/language.variables.scope.php
欲了解更多信息:http://php.net/manual/en/language.variables.scope.php
#1
49
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只有函数作用域 - 控制结构,如果不引入新的作用域。但是,如果您使用未声明的变量,它也不介意。 $ i不会存在于main()之外,或者如果if语句失败,但你仍然可以*地回应它。
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:
如果将PHP的error_reporting设置为包含通知,则在尝试使用尚未定义的变量时,它将在运行时发出E_NOTICE错误。所以如果你有:
function main() {
if (rand(0,1) == 0) {
$i = 3;
}
echo $i;
}
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.
代码运行正常,但是一些执行将回显'3'(当if成功时),并且一些将引发E_NOTICE并且什么都不回显,因为$ i将不在echo语句的范围内定义。
Outside of the function, $i
will never be defined (because the function has a different scope).
在函数之外,永远不会定义$ i(因为函数具有不同的范围)。
For more info: http://php.net/manual/en/language.variables.scope.php
欲了解更多信息:http://php.net/manual/en/language.variables.scope.php