1
0
mirror of https://github.com/jupeter/clean-code-php.git synced 2025-09-25 21:49:04 +02:00

Add null coalescing section

This commit is contained in:
Leonardo do Carmo
2020-04-09 12:31:20 -03:00
parent 8f6c4ee1a0
commit 2a331563d4

View File

@@ -16,6 +16,7 @@
* [Use default arguments instead of short circuiting or conditionals](#use-default-arguments-instead-of-short-circuiting-or-conditionals)
3. [Comparison](#comparison)
* [Use identical comparison](#use-identical-comparison)
* [Null coalescing operator](#null-coalescing-operator)
4. [Functions](#functions)
* [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)
@@ -440,6 +441,28 @@ The comparison `$a !== $b` returns `TRUE`.
**[⬆ 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