这里我们总结if代码块中布尔值的多少对程序进程的影响

if条件小括号内的情况

if括号内为false

毫无疑问,if代码块里面的代码不会继续运行,此时整个程序会跳过条件括号里为false的这个if代码块继续往下运行。

1
2
3
4
if (false) {
echo "This will not be printed";
}
echo "This will be printed because the if condition was false";

在上述代码中,因为 if 条件为 false,echo “This will not be printed”; 不会被执行,程序直接执行 echo “This will be printed because the if condition was false”。

if括号里为true

当 if 括号内条件为 true 时,if 代码块内的代码会执行。但这并不意味着整个程序会不受影响地继续运行。
取决于 if 代码块内的代码:
如果 if 代码块内有 return、exit 或 die 等终止程序或函数的语句,程序或函数的执行会被终止。
比如:

1
2
3
4
5
6
7
8
function exampleFunction() {
if (true) {
echo "This will be printed";
return;
}
echo "This will not be printed because of the return statement";
}
exampleFunction();

在这种情况下,if代码块内因为有return,所以在同一函数代码空间的echo语句不会被执行。也就是在这一层代码空间内,程序的运行确实被终止了。
这就引出了我们接下来要说的一种情况:

return的辨析

其实我们在这里可以把return,die,exit这几个对程序运行都有影响的一起说了。
1.首先是return,它在,不管是返回什么布尔值,都会使同一空间代码停止运行,
如果在函数内,它就会使return之后的代码无法运行,如果在类中,也是一样,而我们不推荐把它放在全局代码空间中,这样会使得整个程序停止运行。
例如:

1
2
3
4
5
6
7
8
9
function exampleFunction() {
echo "Before return<br>";
// 这里的条件可以根据需要修改
if (true) {
return;
}
echo "After return<br>";
}
exampleFunction();

在函数外依然可以调用这个函数,函数外并没有因为前面函数里面有return而被打断,但是这里就只会
输出:Before return,不会输出After return
在类,即对象class里面情况类似

在文件包含的情况下:
在被包含文件:”included_file.php”内:

1
2
3
4
5
6
7
<?php
echo "Before return in included file<br>";
if (true) {
return;
}
echo "After return in included file<br>";
?>

再在另外一个文件中包含它:

1
2
3
4
<?php
include 'included_file.php';
echo "This is after including the file<br>";
?>

只会输出:

1
2
Before return in included file
This is after including the file

即:在被包含文件自己代码中,return后面的After return in included file没有输出,程序终止。
但是并没有影响去包含这个文件的主文件在后方的”This is after including the file”这句话的输出,
所以在文件包含的情景下,return也只会终止自己文件后方的代码,对主文件没有影响。

2.而die,exit则会直接使整个程序不可运行,没有代码空间的说法。