搜尋
  • 登入
  • 報名
密碼重置成功

關注您感興趣的項目並了解有關它們的最新消息

PHP變數

收藏 148
閱讀 30847
更新時間 2016-09-11

變數

1. 使用見字知意的變數名稱

2. 同一個實體要用相同的變數名稱

3. 使用方便搜尋的名稱 (part 1)

4. 使用方便搜尋的名稱 (part 2)

5. 使用自解釋型變數

6. 避免深層嵌套,儘早返回 (part 1)

7. 避免深層嵌套,儘早返回 (part 2)

8. 少用無意義的變數名稱

9. 不要加入不必要上下文

10. 合理使用參數預設值,沒必要在方法裡再做預設值偵測

1. 使用見字知意的變數名稱

壞:

$ymdstr = $moment->format('y-m-d');

好:

$currentDate = $moment->format('y-m-d');

2. 同一個實體要用相同的變數名稱

壞:

getUserInfo();
getUserData();
getUserRecord();
getUserProfile();

好:

getUser();

3. 使用方便搜尋的名稱 (part 1)

寫程式是用來讀的。所以寫出可讀性高、方便搜尋的程式碼至關重要。命名變數時如果沒有有意義、不好理解,那就是在傷害讀者。請讓你的程式碼方便搜尋。

壞:

// 448 ™ 干啥的?
$result = $serializer->serialize($data, 448);

好:

$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

4. 使用方便搜尋的名稱 (part 2)

壞:

class User
{
    // 7 ™ 干啥的?
    public $access = 7;
}
 
// 4 ™ 干啥的?
if ($user->access & 4) {
    // ...
}
 
// 这里会发生什么?
$user->access ^= 2;

好:

class User
{
    const ACCESS_READ = 1;
    const ACCESS_CREATE = 2;
    const ACCESS_UPDATE = 4;
    const ACCESS_DELETE = 8;
 
    // 默认情况下用户 具有读、写和更新权限
    public $access = self::ACCESS_READ | self::ACCESS_CREATE | self::ACCESS_UPDATE;
}
 
if ($user->access & User::ACCESS_UPDATE) {
    // do edit ...
}
 
// 禁用创建权限
$user->access ^= User::ACCESS_CREATE;

 

5. 使用自解釋型變數

壞:

$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
 
saveCityZipCode($matches[1], $matches[2]);

不錯:

好一些,但強依賴於正規表達式的熟悉程度

$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
 
[, $city, $zipCode] = $matches;
saveCityZipCode($city, $zipCode);

好:

使用有名字的子規則,不用懂正規也能看的懂

$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
 
saveCityZipCode($matches['city'], $matches['zipCode']);

6. 避免深層嵌套,儘早返回 (part 1)

# 太多的if else語句通常會導致你的程式碼難以閱讀,直白優於隱晦

糟糕:

    if (empty($day)) {
        return false;
    }
 
    $openingDays = [
        'friday', 'saturday', 'sunday'
    ];
 
    return in_array(strtolower($day), $openingDays, true);
}

7. 避免深層嵌套,儘早返回 (part 2)
#糟糕的:

function fibonacci(int $n)
{
    if ($n < 50) {
        if ($n !== 0) {
            if ($n !== 1) {
                return fibonacci($n - 1) + fibonacci($n - 2);
            } else {
                return 1;
            }
        } else {
            return 0;
        }
    } else {
        return 'Not supported';
    }
}

好:

function fibonacci(int $n): int
{
    if ($n === 0 || $n === 1) {
        return $n;
    }
 
    if ($n >= 50) {
        throw new \Exception('Not supported');
    }
 
    return fibonacci($n - 1) + fibonacci($n - 2);
}

8. 少用無意義的變數名稱

別讓讀你的程式碼的人猜你寫的變數是什麼意思。寫清楚好過模糊不清。

壞:

$l = ['Austin', 'New York', 'San Francisco'];
 
for ($i = 0; $i < count($l); $i++) {
    $li = $l[$i];
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
  // 等等, `$li` 又代表什么?
    dispatch($li);
}

好:

$locations = ['Austin', 'New York', 'San Francisco'];
 
foreach ($locations as $location) {
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    dispatch($location);
}

9. 不要加入不必要上下文

如果從你的類別名稱、物件名稱已經可以得知一些訊息,就別再在變數名稱裡重複。

壞:

 class Car
{
    public $carMake;
    public $carModel;
    public $carColor;
 
    //...
}

好:

 class Car
{
    public $make;
    public $model;
    public $color;
 
    //...
}

10. 合理使用參數預設值,沒必要在方法裡再做預設值偵測

# 不好:

不好,$breweryName 可能為 NULL.

 function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
{
    // ...
}

還行:

比上一個好理解一些,但最好能控制變數的值

 function createMicrobrewery($name = null): void
{
    $breweryName = $name ?: 'Hipster Brew Co.';
    // ...
}

好:

如果你的程式只支援 PHP 7 , 那你可以用 type hinting 保證變數 $breweryName 不是 NULL.

 function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
    // ...
}
熱AI工具
Undress AI Tool
Undress AI Tool

免費脫衣圖片

AI Clothes Remover
AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undresser.AI Undress
Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

Stock Market GPT
Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱門工具
記事本++7.3.1
記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版
SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1
禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6
Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版
SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)