php中5中常用优化写法对比

管理员 发布于 3年前   378

php中5中常用优化写法对比,希望对你有帮助


1.PHP删除数组中空值元素,可以直接用array_filter函数

foreach( $arr as $k=>$v){   
    if( !$v )   
        unset( $arr[$k] );   
}  
改
array_filter($arr)

2.foreach循环或数组函数(array_ *)可以处理空数组

$items = [];
// ...
if (count($items) > 0) {
   foreach ($items as $item) {
       // process on $item ...
   }
}
改成
$items = [];
// ...
foreach ($items as $item) {
   // process on $item ...
}

3.将方法的所有内容封装在if语句中

function foo(User $user) {
   if (!$user->isDisabled()) {
       // ...
       // long process
       // ...
   }
}

function foo(User $user) {
   if ($user->isDisabled()) {
       return;
   }

   // ...
   // long process
   // ...
}

4.我们经常需要检查是否已定义变量(而不是null)。在PHP中,我们可以使用isset函数来做到这一点。而且,魔术,它可以采用多个参数!

$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']
}

$a = null;
$b = null;
$c = null;
// ...

if (!isset($a, $b, $c)) {
   throw new Exception("undefined variable");
}
// or
if (isset($a, $b, $c)) {
   // process with $a, $b et $c
}
// or
$items = [];
//...
if (isset($items['user'], $items['user']['id'])) {
   // process with $items['user']['id']
}


5.结合使用echo方法和sprintf,我们可以简单地使用printf方法

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

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


6.in_array和array_keys的联合使用,可以使用array_key_exists替换。

$items = [
   'one_key' => 'John',
   'search_key' => 'Jane',
];

if (in_array('search_key', array_keys($items))) {
   // process
}

$items = [
   'one_key' => 'John',
   'search_key' => 'Jane',
];

if (array_key_exists('search_key', $items)) {
   // process
}

收藏一下啦


请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

该博客于2020-12-7日,后端基于go语言的beego框架开发
前端页面使用Bootstrap可视化布局系统自动生成

是我仿的原来我的TP5框架写的博客,比较粗糙,底下是入口
侯体宗的博客

      订阅博客周刊

文章标签

友情链接

HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群
侯体宗的博客