【相关学习推荐:php图文教程】
这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);}// orif (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);}// orif (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}复制代码
感谢您的阅读,如果对您有帮助,欢迎关注crmeb掘金号。码云上有我们开源的商城项目,知识付费项目,均是基于php开发,学习研究欢迎使用,关注我们保持联系!
相关学习推荐:php编程(视频)
以上就是一定要改掉 这5个php编程中的不良习惯!的详细内容。