1. 程式人生 > 程式設計 >PHP程式設計一定要改掉的5個不良習慣

PHP程式設計一定要改掉的5個不良習慣

這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,$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);

這段程式碼可能在微笑,但是我碰巧寫了一段時間。而且我仍然看到很多!除了結合echosprintf,我們可以簡單地使用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_arrayarray_keys。所有這些都可以使用array_key_exists替換。

$items = [
 'one_key' => 'John',];if (array_key_exists('search_key',$items)) {
 // process
}

我們還可以使用isset來檢查值是否是null。

if (isset($items['search_key'])) {
 // process
}

以上就是PHP程式設計一定要改掉的5個不良習慣的詳細內容,更多關於php 不良習慣的資料請關注我們其它相關文章!