請糾正這5個PHP編碼小陋習
阿新 • • 發佈:2020-11-06
在做過大量的程式碼審查後,我經常看到一些重複的錯誤,以下是糾正這些錯誤的方法。
在迴圈之前測試陣列是否為空
$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 }