网页标准化设计使用的优势
- 时间:
- 地点:
2023最新开源城市站群cms系统【万站巅云站群CMS系统源码程序】
精美大气网络公司网站模板,网络公司网站源码,专业网络公司网页设计
西部数码代理平台模板 -西部数码代理价格自动获取
最新一键建站系统源码,saas建站系统源码,自助建站整站源码,站长源码,自助建站系统源码,源码搭建教程,开源自助建站系统,php智能建站系统,可视化网站框架源码
最新首发自助建站系统源码,傻瓜式一键建站系统源码,高度开源支持专业在线自助建站服务平台搭建
巅云拖拽式VUE前端框架4.0,可视化拖拽编辑器,实现了h5可视化拖拽生成工具,前端大屏布局,组件化模板机制
在做过大量的代码审查后,我经常看到一些重复的错误,以下是纠正这些错误的方法。
$items = []; // ... if (count($items) > 0) { foreach ($items as $item) { // process on $item ... } }
foreach 以及数组函数 (array_*) 可以处理空数组。
不需要先进行测试可减少一层缩进
$items = []; // ... foreach ($items as $item) { // process on $item ... }
function foo(User $user) { if (!$user->isDisabled()) { // ... // long process // ... } }
这不是 PHP 特有的情况,不过我经常碰到此类情况。你可以通过提前返回来减少缩进。
所有主要方法处于第一个缩进级别
function foo(User $user) { if ($user->isDisabled()) { return; } // ... // 其他代码 // ... }
你可能遇到以下情况:
$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 函数可以用于检测该变量,而且该函数可以一次接受多个参数,所以一下代码可能更好:
$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"] }
$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 }
到此这篇关于常见的5个PHP编码小陋习以及优化实例讲解的文章就介绍到这了,更多相关常见的5个PHP编码小陋习内容请搜索IT博客社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT博客社区!
notmore
联系我们
合作或咨询可通过如下方式:
QQ/微信:123456
网址:www.xxxx.cn
微信公众号:车展门票
关于本站
Copyright 车展网 www.xxxx.cn Reserved渝ICP备xxxxxxxx号
关注我们