在项目的每一次提交之后,我都会进行大量代码审查,会经常看到一些重复出现的错误。以下这五个错误应该要及时纠正,这是纠正它们的方法。
$items = [];
// ...
if (count($items) > 0) {
foreach ($items as $item) { // process on $item ...
}
}
-
不需要先进行测试 -
可以减少一层缩进
function foo(User $user) {
if ($user->isDisabled()) {
return;
} // ...
// long process
// ...
}
$a = null;
$b = null;
$c = null;
// ...
if (!isset($a) || !isset($b) || !isset($c)) {
throw new Exception("undefined variable");
}
// or
if (isset($a) && isset($b) && isset($c) {
// process with $a, $b et $c
}
// or
$items = [];
//...
if (isset($items['user']) && isset($items['user']['id']) {
// process with $items['user']['id']
}
null
)。在PHP中,我们可以使用isset函数来做到这一点。而且该函数一次可以接受多个参数!$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}
if (isset($items['search_key'])) {
// process
}

《PHP经典编程265例》pdf网盘下载
链接:https://pan.baidu.com/s/1ppi1SC56p5JEapgx0-IFig
提取码:rrqr
复制这段内容后打开百度网盘手机App,操作更方便哦
转载请注明:XAMPP中文组官网 » PHP经典书籍《PHP经典编程265例》pdf下载