必须纠正得5个PHP编码小陋习

朱雀 2021-01-29 17:39 518阅读 0赞

在循环之前测试数组是否为空

  1. $items = [];
  2. // ...
  3. if (count($items) > 0) {
  4. foreach ($items as $item) {
  5. // process on $item ...
  6. }
  7. }

foreach 以及数组函数 (array_*) 可以处理空数组。

不需要先进行测试
可减少一层缩进

  1. $items = [];
  2. // ...
  3. foreach ($items as $item) {
  4. // process on $item ...
  5. }

将代码内容封装到一个 if 语句汇总

  1. function foo(User $user) {
  2. if (!$user->isDisabled()) {
  3. // ...
  4. // long process
  5. // ...
  6. }
  7. }

这不是 PHP 特有的情况,不过我经常碰到此类情况。你可以通过提前返回来减少缩进。

所有主要方法处于第一个缩进级别

  1. function foo(User $user) {
  2. if ($user->isDisabled()) {
  3. return;
  4. }
  5. // ...
  6. // 其他代码
  7. // ...
  8. }

多次调用 isset 方法
你可能遇到以下情况:

  1. $a = null;
  2. $b = null;
  3. $c = null;
  4. // ...
  5. if (!isset($a) || !isset($b) || !isset($c)) {
  6. throw new Exception("undefined variable");
  7. }
  8. // 或者
  9. if (isset($a) && isset($b) && isset($c) {
  10. // process with $a, $b et $c
  11. }
  12. // 或者
  13. $items = [];
  14. //...
  15. if (isset($items['user']) && isset($items['user']['id']) {
  16. // process with $items['user']['id']
  17. }

我们经常需要检查变量是否已定义,php 提供了 isset 函数可以用于检测该变量,而且该函数可以一次接受多个参数,所以一下代码可能更好:

  1. $a = null;
  2. $b = null;
  3. $c = null;
  4. // ...
  5. if (!isset($a, $b, $c)) {
  6. throw new Exception("undefined variable");
  7. }
  8. // 或者
  9. if (isset($a, $b, $c)) {
  10. // process with $a, $b et $c
  11. }
  12. // 或者
  13. $items = [];
  14. //...
  15. if (isset($items['user'], $items['user']['id'])) {
  16. // process with $items['user']['id']
  17. }

echo 和 sprintf 方法一起使用
$name = “John Doe”;
echo sprintf(‘Bonjour %s’, $name);
看到这段代码你可能会想笑,不过我的确这样写了一段时间,而且我仍然会看到很多这样写的!其实 echo 和 sprintf 并不需同时使用,printf 就可以完全实现打印功能。$name = “John Doe”;
printf(‘Bonjour %s’, $name);
通过组合两种方法检查数组中是否存在键

  1. $items = [
  2. 'one_key' => 'John',
  3. 'search_key' => 'Jane',
  4. ];
  5. if (in_array('search_key', array_keys($items))) {
  6. // process
  7. }

我经常看到的最后一个错误是 in_array 和 array_keys 的联合使用。所有这些都可以使用 array_key_exists 替换。

  1. $items = [
  2. 'one_key' => 'John',
  3. 'search_key' => 'Jane',
  4. ];
  5. if (array_key_exists('search_key', $items)) {
  6. // process
  7. }

我们还可以使用 isset 来检查值是否不是 null。

  1. if (isset($items['search_key'])) {
  2. // process
  3. }

发表评论

表情:
评论列表 (有 0 条评论,518人围观)

还没有评论,来说两句吧...

相关阅读

    相关 19 JavaScript 编码技巧

    这篇文章适合任何一位基于JavaScript开发的开发者。我写这篇文章主要涉及JavaScript中一些简写的代码,帮助大家更好理解一些JavaScript的基础。希望这些代码