转载自 PHP 论坛:https://learnku.com/php/t/49583
在做过大量的代码审查后,我常常看到一些反复的谬误,以下是纠正这些谬误的办法。
在循环之前测试数组是否为空
$items = [];// ...if (count($items) > 0) {foreach ($items as $item) {// process on $item ...}}
foreach
以及数组函数 (array_*
) 能够解决空数组。
- 不须要先进行测试
- 可缩小一层缩进
$items = [];// ...foreach ($items as $item) {// process on $item ...}
将代码内容封装到一个 if 语句汇总
function foo(User $user) {if (!$user->isDisabled()) {// ...// long process// ...}}
这不是 PHP 特有的状况,不过我常常碰到此类情况。你能够通过提前返回来缩小缩进。
所有次要办法处于第一个缩进级别
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}
探讨请返回业余的 PHP 论坛:https://learnku.com/php/t/49583