php中5中常用优化写法对比
php  /  管理员 发布于 1年前   442
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
}
收藏一下啦
博主 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 @路过的靓仔:cdn静态资源被墙,已修复..GGGGGGGGG 在
layui框架常用输入框介绍中评论 写的很好解决问题..路过的靓仔 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 剩下好多 wait 状态的..激光豆芽 在
为什么你不能安逸?国内996为什么没有国外955香?中评论 国内现在无意义的内卷太多了..激光豆芽 在
阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 厉害了..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号