PHP variables


variable

1. Use variable names that make sense

2. The same entity must use the same variable name

3. Use search-friendly names (part 1)

4. Use search-friendly names (part 2)

5. Use self-explanatory variables

6. Avoid deep nesting and return as early as possible (part 1)

7. Avoid deep nesting and return as early as possible (part 2)

8. Use less meaningless variable names

9. Don’t add unnecessary context

10. Use parameter default values ​​reasonably, there is no need to do default value detection in the method

1. Use meaningful variable names

bad:

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

good:

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

2. The same entity must use the same variable name

bad:

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

good:

getUser();

3. Use search-friendly names (part 1)

Code is written to be read. So it’s crucial to write code that’s highly readable and searchable. If you name variables that are not meaningful and easy to understand, you are doing your readers a disservice. Please make your code searchable.

bad:

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

good:

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

4. Use search-friendly names (part 2)

bad:

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

good:

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. Use self-explanatory variables

bad:

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

good:

Better, but strongly dependent on familiarity with regular expressions

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

good:

Use sub-rules with names, you don’t need to understand regular rules to understand them

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

6. Avoid deep nesting and return as early as possible (part 1)

Too many if else statements usually make your code difficult to read. It is better to be explicit than to be vague.

Oops:

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

7. Avoid deep nesting and return early (part 2)
Bad:

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';
    }
}

good:

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. Use less meaningless variable names

Don't let people reading your code guess what the variables you write mean. It is better to write clearly than vaguely.

bad:

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

good:

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

9. Don’t add unnecessary context

If some information can already be learned from your class name or object name, don't repeat it in the variable name.

bad:

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

good:

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

10. Use parameter default values ​​reasonably, there is no need to do default value detection in the method

not good:

No, $breweryName may be NULL.

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

good:

It's easier to understand than the previous one, but it's better to be able to control the value of the variable.

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

good:

If your program only supports PHP 7, you can use type hinting to ensure that the variable $breweryName is not NULL.

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