這篇文章主要講解了“PHP編程中的壞習慣”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“PHP編程中的壞習慣”吧!
php是一個嵌套的縮寫名稱,是英文超級文本預處理語言,它的語法混合了C、Java、Perl以及php自創新的語法,主要用來做網站開發,許多小型網站都用php開發,因為php是開源的,從而使得php經久不衰。
這5個PHP編程中的不良習慣,一定要改掉 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->isDisafunction foo(User $user) { if (!$user->isDisabled()) { // ... // long process // ... } }bled()) { // ... // long process // ... } }
這不是特定于PHP的,但我經??吹剿?。你可以通過提前返回,來減少縮進級別的極簡代碼! 該函數的所有“有用”主體現在處于第一個縮進級別
function foo(User $user) { if ($user->isDisabled()) { return; } // ... // long process // ... }
多次調用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'] }
我們經常需要檢查是否已定義變量(而不是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'] }
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 }
感謝各位的閱讀,以上就是“PHP編程中的壞習慣”的內容了,經過本文的學習后,相信大家對PHP編程中的壞習慣這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。