常見的5個PHP編碼小陋習以及優(yōu)化實例講解
在做過大量的代碼審查后,我經(jīng)??吹揭恍┲貜偷腻e誤,以下是糾正這些錯誤的方法。
在循環(huán)之前測試數(shù)組是否為空
$items = []; // ... if (count($items) > 0) { foreach ($items as $item) { // process on $item ... } }
foreach 以及數(shù)組函數(shù) (array_*) 可以處理空數(shù)組。
不需要先進行測試可減少一層縮進
$items = []; // ... foreach ($items as $item) { // process on $item ... }
將代碼內容封裝到一個 if 語句匯總
function foo(User $user) { if (!$user->isDisabled()) { // ... // long process // ... } }
這不是 PHP 特有的情況,不過我經(jīng)常碰到此類情況。你可以通過提前返回來減少縮進。
所有主要方法處于第一個縮進級別
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'] }
我們經(jīng)常需要檢查變量是否已定義,php 提供了 isset 函數(shù)可以用于檢測該變量,而且該函數(shù)可以一次接受多個參數(shù),所以一下代碼可能更好:
$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 就可以完全實現(xiàn)打印功能。
$name = "John Doe"; printf('Bonjour %s', $name);
通過組合兩種方法檢查數(shù)組中是否存在鍵
$items = [ 'one_key' => 'John', 'search_key' => 'Jane', ]; if (in_array('search_key', array_keys($items))) { // process }
我經(jīng)??吹降淖詈笠粋€錯誤是 in_array 和 array_keys 的聯(lián)合使用。所有這些都可以使用 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 }
到此這篇關于常見的5個PHP編碼小陋習以及優(yōu)化實例講解的文章就介紹到這了,更多相關常見的5個PHP編碼小陋習內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Laravel5.5 視圖 - 創(chuàng)建視圖和數(shù)據(jù)傳遞示例
今天小編就為大家分享一篇Laravel5.5 視圖 - 創(chuàng)建視圖和數(shù)據(jù)傳遞示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10Yii2搭建后臺并實現(xiàn)rbac權限控制完整實例教程
這篇文章主要介紹了Yii2搭建后臺并實現(xiàn)rbac權限控制完整實例教程的相關資料,需要的朋友可以參考下2016-04-04