这篇文章将为大家详细讲解有关PHP编码规范的案例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
在做过大量的代码审查后,我经常看到一些重复的错误,以下是纠正这些错误的方法。
一:在循环之前测试数组是否为空
$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编码规范的案例分析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。