如何减少 PHP 中 if-else 语句的数量?

2022-01-07 00:00:00 nested if-statement readability php

我发现有很多 if-else 语句,尤其是嵌套的 if else 语句,这些语句使我的代码可读性较差.PHP中如何减少if else语句的数量?

I found that there are many if-else statements, especially nested if else statements, these statements make my code less readable. How to reduce the number of if else statements in PHP?

我的建议如下:1.在合适的时候使用switch语句;2.可行时使用exit()语句;3. 可行时使用三元语句;

My tips are as follows: 1.Use a switch statement when it is suitable; 2.use exit() statement when it is feasible; 3. Use ternary statement when it is feasible;

是否有其他技巧可以减少 if else 语句,尤其是嵌套的 if-else 语句?

Are there other tips that can reduce if else statements, especially nested if-else statements?

推荐答案

将您的代码重构为更小的工作单元.太多的条件逻辑是一种代码味道,通常表明您的函数需要重构.

Refactor your code into smaller work units. Too much conditional logic is a code-smell and usually indicates that your function needs to be refactored.

相关文章