在包含文件中使用 PHP Return 与 Else
Use of PHP Return vs Else in include files
我知道以下两个都有效,但我想知道哪个被认为是最佳解决方案。
我在包含的文件中有一些代码。如果满足某些条件,我想停止执行包含文件中的剩余代码并return调用文件。
示例 1 在包含的文件中有以下代码:
$error = false;
// Some code here that can trigger $error = true
if ($error) {
return; // return to calling file
}
// More code below, only to be executed if $error = false
示例 2 在包含的文件中有以下代码:
$error = false;
// Some code here that can trigger $error = true
if (!$error) {
// Execute remaining code within the conditional statement
}
// Return to the calling file
提前致谢。
几乎没有区别,但我使用 1-st 方法 的原因很简单:我希望主要代码主体更显眼,而不是隐藏在括号中并打算。
我更喜欢示例 1,因为早期的 return 模式导致代码缩进较少。如果像 示例 2 中那样有多个检查,您将以缩进代码结尾:
$error = false;
// Some code here that can trigger $error = true
if (!$error) {
// Execute remaining code within the conditional statement
// Some more code here that can trigger $error = true
if (!$error) {
// Execute remaining code within the conditional statement
}
}
// Return to the calling file
这会迫使你不必要地记住 "this block is in the successful branch of the if
"。
包含与调用函数不同,因此谈论“停止执行包含文件中的剩余代码并return调用文件"
在 PHP 中包含某些内容仅意味着将一个文件中的文本放入另一个文件中的特定位置。
我知道以下两个都有效,但我想知道哪个被认为是最佳解决方案。
我在包含的文件中有一些代码。如果满足某些条件,我想停止执行包含文件中的剩余代码并return调用文件。
示例 1 在包含的文件中有以下代码:
$error = false;
// Some code here that can trigger $error = true
if ($error) {
return; // return to calling file
}
// More code below, only to be executed if $error = false
示例 2 在包含的文件中有以下代码:
$error = false;
// Some code here that can trigger $error = true
if (!$error) {
// Execute remaining code within the conditional statement
}
// Return to the calling file
提前致谢。
几乎没有区别,但我使用 1-st 方法 的原因很简单:我希望主要代码主体更显眼,而不是隐藏在括号中并打算。
我更喜欢示例 1,因为早期的 return 模式导致代码缩进较少。如果像 示例 2 中那样有多个检查,您将以缩进代码结尾:
$error = false;
// Some code here that can trigger $error = true
if (!$error) {
// Execute remaining code within the conditional statement
// Some more code here that can trigger $error = true
if (!$error) {
// Execute remaining code within the conditional statement
}
}
// Return to the calling file
这会迫使你不必要地记住 "this block is in the successful branch of the if
"。
包含与调用函数不同,因此谈论“停止执行包含文件中的剩余代码并return调用文件"
在 PHP 中包含某些内容仅意味着将一个文件中的文本放入另一个文件中的特定位置。