无为清净楼资源网 Design By www.qnjia.com
在做过大量的代码审查后,我经常看到一些重复的错误,以下是纠正这些错误的方法。
在循环之前测试数组是否为空
$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 }
无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com
暂无评论...
更新日志
2024年09月25日
2024年09月25日
- 黄心懋1991-轻忧郁【滚石】【WAV+CUE】
- 群星.2000-大地金曲世纪回顾2CD【大地】【WAV+CUE】
- 王菲.1996-浮躁(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 群星.2022-传家电视剧原声带【东阳欢娱】【FLAC分轨】
- 《摇滚教父 伍佰黄金精选 2CD》 [WAV+CUE][1GB]
- 《凤凰传奇 我从草原来》[WAV/分轨][400MB]
- 《叶倩文 真心真意过一生》[WAV+CUE][400MB]
- 潘越云.1985-世间女子(滚石25周年经典复刻版)【滚石】【WAV+CUE】
- 陈柏宇.2009-CANT.BE.HALF【SONY】【WAV+CUE】
- 李明依.1989-小女生【滚石】【WAV+CUE】
- 《李荣浩 新时代创作新人王》[WAV分轨][310MB]
- 《黑鸭子与马头琴 史上最动听草原音乐》[WAV+CUE][320MB]
- 《汽车发烧音乐精选CD18》[FLAC+CUE][7.1G]
- 郑希怡.2004-Perfect.Date【英皇娱乐】【FLAC分轨】
- 群星.1994-宝丽金超级孖宝2CD【宝丽金】【WAV+CUE】