推薦:《PHP視頻教程》

在做過大量的代碼審查后,我經(jīng)常看到一些重復(fù)的錯(cuò)誤,以下是糾正這些錯(cuò)誤的方法。
一:在循環(huán)之前測(cè)試數(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 ...
}二:將代碼內(nèi)容封裝到一個(gè) if 語句匯總
function foo(User $user) {
if (!$user->isDisabled()) {
// ...
// long process
// ...
}
}這不是 PHP 特有的情況,不過我經(jīng)常碰到此類情況。你可以通過提前返回來減少縮進(jìn)。
所有主要方法處于第一個(gè)縮進(jìn)級(jí)別
function foo(User $user) {
if ($user->isDisabled()) {
return;
}
// ...
// 其他代碼
// ...
}三:多次調(diào)用 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ù)可以用于檢測(cè)該變量,而且該函數(shù)可以一次接受多個(gè)參數(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);這段代碼可能在微笑,但是我碰巧寫了一段時(shí)間。而且我仍然看到很多!不用結(jié)合echo和sprintf,我們可以簡(jiǎn)單地使用printf方法。
$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)常看到的最后一個(gè)錯(cuò)誤是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
}原文地址:https://dev.to/klnjmm/5-bad-habits-to-lose-in-php-2j98
譯文地址:https://learnku.com/php/t/49583
分享題目:你可能要糾正這5個(gè)PHP編碼小陋習(xí)!
本文URL:http://chinadenli.net/article18/cpdogp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、微信公眾號(hào)、用戶體驗(yàn)、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站策劃、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)