你可能要纠正这5个PHP编码小陋习!-php教程

资源魔 52 0

保举:《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->isDisabled()) {
        // ...
        // long process
        // ...
    }
}

这没有是 PHP 独有的状况,不外我常常碰着此类状况。你能够经过提前前往来缩小缩进。

一切次要办法处于第一个缩进级别

function foo(User $user) {
    if ($user->isDisabled()) {
        return;
    }

    // ...
    // 其余代码
    // ...
}

三:屡次挪用 isset 办法

你可能遇到如下状况:

$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']
}

四: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
}

原文地点:https://dev.to/klnj妹妹/5-bad-habits-to-lose-in-php-2j98

译文地点:https://learnku.com/php/t/49583

以上就是你可能要纠正这5个PHP编码小陋习!的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!