Skip to content

Commit 3d5a1b0

Browse files
author
Tomáš Votruba
authored
Merge pull request zedr#26 from peter-gribanov/default_arguments
[Bugfix] Use default arguments in PHP 7+
2 parents fd878a3 + aa24deb commit 3d5a1b0

1 file changed

Lines changed: 25 additions & 7 deletions

File tree

README.md

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -186,22 +186,40 @@ class Car
186186

187187
### Use default arguments instead of short circuiting or conditionals
188188

189-
**Bad:**
189+
**Not good:**
190+
191+
This is not good because `$breweryName` can be `NULL`.
192+
190193
```php
191-
function createMicrobrewery($name = null) {
192-
$breweryName = $name ?: 'Hipster Brew Co.';
193-
// ...
194+
function createMicrobrewery($breweryName = 'Hipster Brew Co.')
195+
{
196+
   // ...
194197
}
195-
196198
```
197199

198-
**Good**:
200+
**Not bad:**
201+
202+
This opinion is more understandable than the previous version, but it better controls the value of the variable.
203+
199204
```php
200-
function createMicrobrewery($breweryName = 'Hipster Brew Co.') {
205+
function createMicrobrewery($name = null)
206+
{
207+
   $breweryName = $name ?: 'Hipster Brew Co.';
201208
// ...
202209
}
210+
```
211+
212+
**Good**:
213+
214+
If you support only PHP 7+, then you can use [type hinting](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) and be sure that the `$breweryName` will not be `NULL`.
203215

216+
```php
217+
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.')
218+
{
219+
   // ...
220+
}
204221
```
222+
205223
**[⬆ back to top](#table-of-contents)**
206224
## **Functions**
207225
### Function arguments (2 or fewer ideally)

0 commit comments

Comments
 (0)