Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

php - If you create a variable inside a if statement is it available outside the if statement?

If you have an if statement like this:

<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
?>

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
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

To illustrate:

if (true)  { $a = 5; }    var_dump($a == 5);   // true

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

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

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 short circuits and the execution does not arrive at $d = 5, so the $d variable will not be defined.

For more about the PHP scope, read the variable scope manual page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...