常见的5个PHP编码小陋习以及优化实例讲解

吾爱主题 阅读:127 2021-11-08 14:57:00 评论:0

在做过大量的代码审查后,我经常看到一些重复的错误,以下是纠正这些错误的方法。

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

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

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

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

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

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

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

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

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

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

多次调用 isset 方法

你可能遇到以下情况:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 $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 函数可以用于检测该变量,而且该函数可以一次接受多个参数,所以一下代码可能更好:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 $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'] }<br>

echo 和 sprintf 方法一起使用

?
1 2 $name = "John Doe" ; echo sprintf( 'Bonjour %s' , $name );

看到这段代码你可能会想笑,不过我的确这样写了一段时间,而且我仍然会看到很多这样写的!其实 echo 和 sprintf 并不需同时使用,printf 就可以完全实现打印功能。

?
1 2 $name = "John Doe" ; printf( 'Bonjour %s' , $name );

通过组合两种方法检查数组中是否存在键

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

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

?
1 2 3 4 5 6 7 8 9 10 11 12 13 $items = [    'one_key' => 'John' ,    'search_key' => 'Jane' , ];   if ( array_key_exists ( 'search_key' , $items )) {    // process } 我们还可以使用 isset 来检查值是否不是 null。   if (isset( $items [ 'search_key' ])) {    // process }

到此这篇关于常见的5个PHP编码小陋习以及优化实例讲解的文章就介绍到这了,更多相关常见的5个PHP编码小陋习内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/liuxingjiaoyuC/article/details/111029164

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容