问题描述
如果你有这样的 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 语句之外使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2