常春岛资源网 Design By www.syssdc.com
这5个PHP编程中的不良习惯,一定要改掉 PHP世界上最好的语言!
测试循环前数组是否为空?
$items = []; // ... if (count($items) > 0) { foreach ($items as $item) { // process on $item ... }}
foreach
循环或数组函数(array_*)
可以处理空数组。
- 不需要先进行测试
- 可以减少一层缩进
$items = []; // ... foreach ($items as $item) { // process on $item ... }
将方法的所有内容封装在if语句中
function foo(User $user) { if (!$user->isDisafunction foo(User $user) { if (!$user->isDisabled()) { // ... // long process // ... } }bled()) { // ... // long process // ... } }
这不是特定于PHP的,但我经常看到它。你可以通过提前返回,来减少缩进级别的极简代码! 该函数的所有“有用”主体现在处于第一个缩进级别
function foo(User $user) { if ($user->isDisabled()) { return; } // ... // long process // ... }
多次调用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'] }
我们经常需要检查是否已定义变量(而不是null
)。 在PHP中,我们可以使用isset函数来做到这一点。而且该函数一次可以接受多个参数!
$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结合使用
$name = "John Doe"; echo sprintf('Bonjour %s', $name);
这段代码可能在微笑,但是我碰巧写了一段时间。而且我仍然看到很多!除了结合echo
和sprintf
,我们可以简单地使用printf
方法。
$name = "John Doe"; printf('Bonjour %s', $name);
通过组合两种方法检查数组中键的存在
$items = [ 'one_key' => 'John', 'search_key' => 'Jane', ];if (in_array('search_key', array_keys($items))) { // process }
最后一个错误我看到的往往是联合使用in_array
和array_keys
。所有这些都可以使用array_key_exists替换。
$items = [ 'one_key' => 'John', 'search_key' => 'Jane', ];if (array_key_exists('search_key', $items)) { // process }
我们还可以使用isset来检查值是否是null。
if (isset($items['search_key'])) { // process }
以上就是PHP编程一定要改掉的5个不良习惯的详细内容,更多关于php 不良习惯的资料请关注其它相关文章!
常春岛资源网 Design By www.syssdc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
常春岛资源网 Design By www.syssdc.com
暂无评论...
更新日志
2025年05月05日
2025年05月05日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]