这5个PHP编程中的不良习惯,一定要改掉 PHP世界上最好的语言!
测试循环前数组是否为空?
?
|
1
2
3
4
5
|
$items = [];
// ...
if (count($items) > 0) {
foreach ($items as $item) { // process on $item ...
}}
|
foreach循环或数组函数(array_*)可以处理空数组。
- 不需要先进行测试
- 可以减少一层缩进
?
|
1
2
3
4
|
$items = [];
// ...
foreach ($items as $item) { // process on $item ...
}
|
将方法的所有内容封装在if语句中
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function foo(User $user) {
if (!$user->isDisafunction foo(User $user) {
if (!$user->isDisabled()) {
// ...
// long process
// ...
}
}bled()) {
// ...
// long process
// ...
}
}
|
这不是特定于PHP的,但我经常看到它。你可以通过提前返回,来减少缩进级别的极简代码! 该函数的所有“有用”主体现在处于第一个缩进级别
?
|
1
2
3
4
5
6
7
|
function foo(User $user) {
if ($user->isDisabled()) {
return;
} // ...
// long process
// ...
}
|
多次调用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");
}
// 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']
}
|
我们经常需要检查是否已定义变量(而不是null)。 在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");
}
// 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']
}
|
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
|
$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
|
$items = [
'one_key' => 'John',
'search_key' => 'Jane',
];if (array_key_exists('search_key', $items)) {
// process
}
|
我们还可以使用isset来检查值是否是null。
?
|
1
2
3
|
if (isset($items['search_key'])) {
// process
}
|
以上就是PHP编程一定要改掉的5个不良习惯的详细内容,更多关于php 不良习惯的资料请关注快网idc其它相关文章!
原文链接:https://juejin.im/post/6872242391140155400?utm_source=tuicool&utm_medium=referral
相关文章
猜你喜欢
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 61
-
2025-05-27 50
-
2025-05-29 26
-
2025-05-27 53
-
详解Spring Cloud中Hystrix 线程隔离导致ThreadLocal数据丢失
2025-05-29 60
热门评论

