首頁  >  文章  >  後端開發  >  你可能要修正這5個PHP編碼小陋習!

你可能要修正這5個PHP編碼小陋習!

藏色散人
藏色散人轉載
2020-09-14 13:34:144358瀏覽

推薦:《你可能要修正這5個PHP編碼小陋習!影片教學

你可能要修正這5個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
        // ...
    }
}

這不是你可能要修正這5個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);

這段程式碼可能在微笑,但我碰巧寫了一段時間。而且我仍然看到很多!不用結合echosprintf,我們可以簡單地使用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_arrayarray_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/klnjmm/5-bad-habits-to-lose-in-php-2j98

翻譯網址:https:/ /learnku.com/php/t/49583

#

以上是你可能要修正這5個PHP編碼小陋習!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除