如果在if语句内创建变量,它是否在if语句外可用? [英] If you create a variable inside a if statement is it available outside the if statement?
问题描述
如果您有如下if语句:
If you have an if statement like this:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
?>
您将能够像这样在if语句之外访问$ c变量:
Would you be able to access the $c variable outside of the if statement like so:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
echo $c
?>
推荐答案
在PHP中,if
没有自己的范围.因此,是的,如果您在if
语句内或块内定义了某些内容,则它将像在外部定义时一样可用(当然,假设块内或if
语句内的代码进入了运行).
In PHP, if
doesn't have its own scope. So yes, if you define something inside the if
statement or inside the block, then it will be available just as if you defined it outside (assuming, of course, the code inside the block or inside the if
statement gets to run).
说明:
if (true) { $a = 5; } var_dump($a == 5); // true
该条件的计算结果为true
,因此该块内的代码将运行.变量$a
被定义.
The condition evaluates to true
, so the code inside the block gets run. The variable $a
gets defined.
if (false) { $b = 5; } var_dump(isset($b)); // false
该条件的计算结果为false
,因此该块内的代码无法运行.变量$b
不会被定义.
The condition evaluates to false
, so the code inside the block doesn't get to run. The variable $b
will not be defined.
if ($c = 5) { } var_dump($c == 5); // true
该条件内的代码开始运行,而$c
被定义为5
($c = 5
).即使赋值发生在if
语句内部,该值也仍然存在于外部,因为if
没有作用域. for
也会发生相同的情况,例如在for ($i = 0, $i < 5; ++$i)
中一样. $i
将保留在for
循环之外,因为for
也不具有作用域.
The code inside the condition gets to run and $c
gets defined as 5
($c = 5
). Even though the assignment happens inside the if
statement, the value does survive outside, because if
has no scope. Same thing happens with for
, just like in, for example, for ($i = 0, $i < 5; ++$i)
. The $i
will survive outside the for
loop, because for
has no scope either.
if (false && $d = 5) { } var_dump(isset($d)); // false
false
短路,并且执行未到达$d = 5
,因此将不会定义$d
变量.
false
short circuits and the execution does not arrive at $d = 5
, so the $d
variable will not be defined.
有关PHP作用域的更多信息,请阅读变量作用域手册页.
For more about the PHP scope, read the variable scope manual page.
这篇关于如果在if语句内创建变量,它是否在if语句外可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!