P

PHP 中需要改掉的 5 个坏习惯

2025-06-09

PHP 中需要改掉的 5 个坏习惯

我做过很多代码审查,经常看到同样的错误。以下是如何纠正这些错误的方法。

循环前测试数组是否为空

$items = [];
// ...
if (count($items) > 0) {
    foreach ($items as $item) {
        // process on $item ...
    }
}
Enter fullscreen mode Exit fullscreen mode

foreach循环或数组函数(array_*)可以处理空数组。

  • 无需事先测试
  • 减少一个缩进级别
$items = [];
// ...
foreach ($items as $item) {
    // process on $item ...
}
Enter fullscreen mode Exit fullscreen mode

如果您想学习如何在没有for/ foreach/while循环的情况下进行编码,我推荐我关于集合的文章(法语)。


将方法的所有内容封装在 if 语句中

function foo(User $user) {
    if (!$user->isDisabled()) {
        // ...
        // long process
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

这个问题并非 PHP 独有,但我经常看到。我已经在关于 calisthenics 对象的文章和关于使用early return减少缩进级别的极简代码的文章中讨论过了。 现在,函数中所有“有用”的代码都位于第一级缩进。

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

    // ...
    // long process
    // ...
}
Enter fullscreen mode Exit fullscreen mode

多次调用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']
}
Enter fullscreen mode Exit fullscreen mode

我们经常需要检查一个变量是否已定义(而不是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']
}
Enter fullscreen mode Exit fullscreen mode

将 echo 方法与 sprintf 结合

$name = "John Doe";
echo sprintf('Bonjour %s', $name);
Enter fullscreen mode Exit fullscreen mode

这段代码可能看起来很滑稽,但我碰巧写过一段时间。而且我仍然经常看到它!我们不用组合echosprintf,而是直接使用printf方法。

$name = "John Doe";
printf('Bonjour %s', $name);
Enter fullscreen mode Exit fullscreen mode

通过结合两种方法检查数组中键的存在

$items = [
    'one_key' => 'John',
    'search_key' => 'Jane',
];

if (in_array('search_key', array_keys($items))) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

我经常看到的最后一个错误是in_array和的联合使用array_keys。所有这些都可以用替换array_key_exists

$items = [
    'one_key' => 'John',
    'search_key' => 'Jane',
];

if (array_key_exists('search_key', $items)) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

我们还可以使用issetwhich 来检查值是否不是null

if (isset($items['search_key'])) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

感谢您的阅读,让我们保持联系!

如果你喜欢这篇文章,请分享。你也可以在Twitter/X上找到我,获取更多 PHP 技巧。

鏂囩珷鏉ユ簮锛�https://dev.to/klnjmm/5-bad-habits-to-lose-in-php-2j98
PREV
站点可靠性工程:Google 高可用性和快乐运营的秘诀
NEXT
理解 JavaScript Promise👩‍💻👨‍💻