## **變量**
### 使用的變量名要表達準確
**差:**
```php
$date = date('Y-m-d', time());
```
**優:**
```php
$currentDate = date('Y-m-d', time());
```
### 同一個實體要用相同的變量名
**差:**
```php
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();
```
**優:**
```php
getUser(); //return array
```
### 利于檢索的變量名
**差:**
```php
if ($error['code'] & $error['code'] === 4) {
// do something...
}
```
**優:**
```php
class Error
{
const NotFound = 404;
const Exception = 500;
const ServiceError = 501;
const RpcError = 505;
}
if ($error['code'] & $error['code'] === Error::NotFound) {
// do something ...
}
```
### 使用自解釋型變量
自解釋型指的是變量名本身解釋了其賦值的內容
**差:**
```php
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches[1], $matches[2]);
```
**不錯:**
好一些,但強依賴于正則表達式的熟悉程度
```php
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
[, $city, $zipCode] = $matches;
saveCityZipCode($city, $zipCode);
```
**優:**
使用帶名字的子規則,不用懂正則也能看的懂
```php
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches['city'], $matches['zipCode']);
```
### 避免深層嵌套,盡早返回 (part 1)
太多的if else語句通常會導致你的代碼難以閱讀,直白優于隱晦
**差:**
```php
function isShopOpen($day): bool
{
if ($day) {
if (is_string($day)) {
$day = strtolower($day);
if ($day === 'friday') {
return true;
} elseif ($day === 'saturday') {
return true;
} elseif ($day === 'sunday') {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
```
**優:**
```php
function isShopOpen(string $day): bool
{
if (empty($day)) {
return false;
}
$openingDays = [
'friday', 'saturday', 'sunday'
];
return in_array(strtolower($day), $openingDays, true);
}
```
### 避免深層嵌套,盡早返回 (part 2)
**差:**
```php
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';
}
}
```
**優:**
```php
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);
}
```
### 少用無意義的變量名
別讓讀你的代碼的人猜你寫的變量是什么意思。
寫清楚好過模糊不清。
**差:**
```php
$l = ['北京', '上海', '杭州'];
for ($i = 0; $i < count($l); $i++) {
$li = $l[$i];
// ...
// ...
// $li表述難懂
dispatch($li);
}
```
**優:**
```php
$locations = ['北京', '上海', '杭州'];
foreach ($locations as $location) {
// ...
// ...
// ...
dispatch($location);
}
```
### 不要添加不必要上下文
如果從你的類名、對象名已經可以得知一些信息,就別再在變量名里重復。
**差:**
```php
class Car
{
public $carMake;
public $carModel;
public $carColor;
//...
}
```
**優:**
```php
class Car
{
public $make;
public $model;
public $color;
//...
}
```
### 合理使用參數默認值,沒必要在方法里再做默認值檢測
**差:**
不好,`$breweryName` 可能為 `NULL`.
```php
function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
{
? ?// ...
}
```
**還行:**
比上一個好理解一些,但最好能控制變量的值
```php
function createMicrobrewery($name = null): void
{
? ?$breweryName = $name ?: 'Hipster Brew Co.';
// ...
}
```
**優:**
PHP 7+環境下可以用 [type hinting](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) 保證變量 `$breweryName` 不是 `NULL`.
```php
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
? ?// ...
}
```