这篇主要给大家分享的是PHP编码过程中的五个常见错误,以及纠正这些错误的方法,对大家PHP编码会有一定的帮助,下文示例有一定的参考价值,感兴趣的朋友接下来跟随小编一起来了解看看吧。
$items = []; // ... if (count($items) > 0) { foreach ($items as $item) { // process on $item ... } }
foreach 以及数组函数 (array_*) 可以处理空数组。
不需要先进行测试可减少一层缩进
$items = []; // ... foreach ($items as $item) { // process on $item ... }
function foo(User $user) { if (!$user->isDisabled()) { // ... // long process // ... } }
这不是 PHP 特有的情况,不过我经常碰到此类情况。你可以通过提前返回来减少缩进。
所有主要方法处于第一个缩进级别
function foo(User $user) { if ($user->isDisabled()) { return; } // ... // 其他代码 // ... }
你可能遇到以下情况:
$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'] }
$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编码过程中的五个常见错误及纠正就介绍到这,上述提到的错误大家一定要注意,希望大家阅读完这篇文章能有所收获。最后,想要了解更多PHP编码错误及纠正,大家可以关注其它的相关文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。