## **变量**
### 使用的变量名要表达准确
**差:**
```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
{
// ...
}
```