mirror of
https://github.com/jupeter/clean-code-php.git
synced 2025-09-26 22:18:59 +02:00
Add null coalescing section
This commit is contained in:
23
README.md
23
README.md
@@ -16,6 +16,7 @@
|
|||||||
* [Use default arguments instead of short circuiting or conditionals](#use-default-arguments-instead-of-short-circuiting-or-conditionals)
|
* [Use default arguments instead of short circuiting or conditionals](#use-default-arguments-instead-of-short-circuiting-or-conditionals)
|
||||||
3. [Comparison](#comparison)
|
3. [Comparison](#comparison)
|
||||||
* [Use identical comparison](#use-identical-comparison)
|
* [Use identical comparison](#use-identical-comparison)
|
||||||
|
* [Null coalescing operator](#null-coalescing-operator)
|
||||||
4. [Functions](#functions)
|
4. [Functions](#functions)
|
||||||
* [Function arguments (2 or fewer ideally)](#function-arguments-2-or-fewer-ideally)
|
* [Function arguments (2 or fewer ideally)](#function-arguments-2-or-fewer-ideally)
|
||||||
* [Function names should say what they do](#function-names-should-say-what-they-do)
|
* [Function names should say what they do](#function-names-should-say-what-they-do)
|
||||||
@@ -440,6 +441,28 @@ The comparison `$a !== $b` returns `TRUE`.
|
|||||||
|
|
||||||
**[⬆ back to top](#table-of-contents)**
|
**[⬆ back to top](#table-of-contents)**
|
||||||
|
|
||||||
|
### Null coalescing operator
|
||||||
|
|
||||||
|
Null coalescing is a new operator [introduced in PHP 7](https://www.php.net/manual/en/migration70.new-features.php). The null coalescing operator `??` has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with `isset()`. It returns its first operand if it exists and is not `null`; otherwise it returns its second operand.
|
||||||
|
|
||||||
|
**Bad:**
|
||||||
|
|
||||||
|
```php
|
||||||
|
if (isset($_GET['name'])) {
|
||||||
|
$name = $_GET['name'];
|
||||||
|
} elseif (isset($_POST['name'])) {
|
||||||
|
$name = $_POST['name'];
|
||||||
|
} else {
|
||||||
|
$name = 'nobody';
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Good:**
|
||||||
|
```php
|
||||||
|
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';
|
||||||
|
```
|
||||||
|
|
||||||
|
**[⬆ back to top](#table-of-contents)**
|
||||||
|
|
||||||
## Functions
|
## Functions
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user