這5個(gè)PHP編程中的不良習(xí)慣,一定要改掉 PHP世界上最好的語(yǔ)言!
測(cè)試循環(huán)前數(shù)組是否為空?
$items = [];
// ...
if (count($items) > 0) {
foreach ($items as $item) { // process on $item ...
}}
foreach
循環(huán)或數(shù)組函數(shù)(array_*)
可以處理空數(shù)組。
- 不需要先進(jìn)行測(cè)試
- 可以減少一層縮進(jìn)
$items = [];
// ...
foreach ($items as $item) { // process on $item ...
}
將方法的所有內(nèi)容封裝在if語(yǔ)句中
function foo(User $user) {
if (!$user->isDisafunction foo(User $user) {
if (!$user->isDisabled()) {
// ...
// long process
// ...
}
}bled()) {
// ...
// long process
// ...
}
}
這不是特定于PHP的,但我經(jīng)??吹剿?。你可以通過(guò)提前返回,來(lái)減少縮進(jìn)級(jí)別的極簡(jiǎn)代碼! 該函數(shù)的所有“有用”主體現(xiàn)在處于第一個(gè)縮進(jìn)級(jí)別
function foo(User $user) {
if ($user->isDisabled()) {
return;
} // ...
// long process
// ...
}
多次調(diào)用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']
}
我們經(jīng)常需要檢查是否已定義變量(而不是null
)。 在PHP中,我們可以使用isset函數(shù)來(lái)做到這一點(diǎn)。而且該函數(shù)一次可以接受多個(gè)參數(shù)!
$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結(jié)合使用
$name = "John Doe";
echo sprintf('Bonjour %s', $name);
這段代碼可能在微笑,但是我碰巧寫(xiě)了一段時(shí)間。而且我仍然看到很多!除了結(jié)合echo
和sprintf
,我們可以簡(jiǎn)單地使用printf
方法。
$name = "John Doe";
printf('Bonjour %s', $name);
通過(guò)組合兩種方法檢查數(shù)組中鍵的存在
$items = [
'one_key' => 'John',
'search_key' => 'Jane',
];if (in_array('search_key', array_keys($items))) {
// process
}
最后一個(gè)錯(cuò)誤我看到的往往是聯(lián)合使用in_array
和array_keys
。所有這些都可以使用array_key_exists替換。
$items = [
'one_key' => 'John',
'search_key' => 'Jane',
];if (array_key_exists('search_key', $items)) {
// process
}
我們還可以使用isset來(lái)檢查值是否是null。
if (isset($items['search_key'])) {
// process
}
以上就是PHP編程一定要改掉的5個(gè)不良習(xí)慣的詳細(xì)內(nèi)容,更多關(guān)于php 不良習(xí)慣的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- PHP大神的十大優(yōu)良習(xí)慣
- php代碼書(shū)寫(xiě)習(xí)慣優(yōu)化小結(jié)
- 編寫(xiě)安全 PHP應(yīng)用程序的七個(gè)習(xí)慣深入分析
- 國(guó)外PHP程序員的13個(gè)好習(xí)慣小結(jié)
- 在PHP中養(yǎng)成7個(gè)面向?qū)ο蟮暮昧?xí)慣
- PHP 引用是個(gè)壞習(xí)慣
- 在PHP中養(yǎng)成7個(gè)面向?qū)ο蟮暮昧?xí)慣
- PHP 編程的 5個(gè)良好習(xí)慣
- 10條PHP編程習(xí)慣助你找工作
- [php]正則表達(dá)式的五個(gè)成功習(xí)慣