经过大量代码审查经验积累,作者发现了一些反复出现的编码问题,并整理了相应的修正策略。
避免在循环执行前单独检测数组是否为空
$items = [];
// ...
if (count($items) > 0) {
foreach ($items as $item) {
// process on $item ...
}
}
PHP中的foreach结构及各类array_*系列函数均具备处理空数组的能力。
省去前置判断能够消除额外的缩进层级。
$items = [];
// ...
foreach ($items as $item) {
// process on $item ...
}
避免将核心逻辑包裹在无必要的条件块中
function foo(User $user) {
if (!$user->isDisabled()) {
// ...
// long process
// ...
}
}
此现象并非PHP独有,但极为常见。采用提前返回(Early Return)模式可有效降低代码缩进深度。
确保主要业务逻辑保持在基础缩进级别。
function foo(User $user) {
if ($user->isDisabled()) {
return;
}
// ...
// 其他代码
// ...
}
避免多次重复调用isset函数
开发者常面临如下场景:
$a = null;
$b = null;
$c = null;
// ...
if (!isset($a) || !isset($b) || !isset($c)) {
throw new Exception("undefined variable");
}
// 或者
if (isset($a) && isset($b) && isset($c) {
// process with $a, $b et $c
}
// 或者
$items = [];
//...
if (isset($items['user']) && isset($items['user']['id']) {
// process with $items['user']['id']
}
当需要验证变量是否已定义时,PHP内置的isset函数支持传入多个参数,因此以下写法更为高效:
$a = null;
$b = null;
$c = null;
// ...
if (!isset($a, $b, $c)) {
throw new Exception("undefined variable");
}
// 或者
if (isset($a, $b, $c)) {
// process with $a, $b et $c
}
// 或者
$items = [];
//...
if (isset($items['user'], $items['user']['id'])) {
// process with $items['user']['id']
}
避免同时使用echo和sprintf进行输出
$name = "John Doe";
echo sprintf('Bonjour %s', $name);
这种写法虽显冗余,但在实际项目中仍屡见不鲜。实际上,echo与sprintf的组合并非必要,直接使用printf即可满足格式化打印需求。
$name = "John Doe";
printf('Bonjour %s', $name);
避免通过组合两种方法检查数组中是否存在键
$items = [
'one_key' => 'John',
'search_key' => 'Jane',
];
if (in_array('search_key', array_keys($items))) {
// process
}
最后一个高频错误是联合使用in_array和array_keys来检测键值。这完全可以用array_key_exists函数替代。
$items = [
'one_key' => 'John',
'search_key' => 'Jane',
];
if (array_key_exists('search_key', $items)) {
// process
}
我们还可以使用 isset 来检查值是否不是 null。
if (isset($items['search_key'])) {
// process
}
以上就是关于常见的5个PHP编码小陋习以及优化实例讲解的文章就介绍到这了,更多相关常见的5个PHP编码小陋习内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!