Skip to content

Commit 783fe13

Browse files
Avoid type-checking (part 2) require PHP 7+
1 parent 02febd7 commit 783fe13

1 file changed

Lines changed: 20 additions & 13 deletions

File tree

‎README.md‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -684,32 +684,39 @@ function travelToTexas($vehicle) {
684684
**[⬆ back to top](#table-of-contents)**
685685

686686
### Avoid type-checking (part 2)
687+
687688
If you are working with basic primitive values like strings, integers, and arrays,
688-
and you can't use polymorphism but you still feel the need to type-check,
689-
you should consider type declaration or strict mode. It provides you with static
690-
typing on top of standard PHP syntax. The problem with manually type-checking is
691-
that doing it well requires so much extra verbiage that the faux "type-safety"
692-
you get doesn't make up for the lost readability. Keep your PHP clean, write good
693-
tests, and have good code reviews. Otherwise, do all of that but with PHP strict
694-
type declaration or strict mode.
689+
and you use PHP 7+ and you can't use polymorphism but you still feel the need to
690+
type-check, you should consider
691+
[type declaration](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration)
692+
or strict mode. It provides you with static typing on top of standard PHP syntax.
693+
The problem with manually type-checking is that doing it well requires so much
694+
extra verbiage that the faux "type-safety" you get doesn't make up for the lost
695+
readability. Keep your PHP clean, write good tests, and have good code reviews.
696+
Otherwise, do all of that but with PHP strict type declaration or strict mode.
695697

696698
**Bad:**
699+
697700
```php
698-
function combine($val1, $val2) {
699-
if (is_numeric($val1) && is_numeric($val2)) {
700-
return $val1 + $val2;
701+
function combine($val1, $val2)
702+
{
703+
if (!is_numeric($val1) || !is_numeric($val2)) {
704+
throw new \Exception('Must be of type Number');
701705
}
702-
703-
throw new \Exception('Must be of type Number');
706+
707+
return $val1 + $val2;
704708
}
705709
```
706710

707711
**Good**:
712+
708713
```php
709-
function combine(int $val1, int $val2) {
714+
function combine(int $val1, int $val2)
715+
{
710716
return $val1 + $val2;
711717
}
712718
```
719+
713720
**[⬆ back to top](#table-of-contents)**
714721

715722
### Remove dead code

0 commit comments

Comments
 (0)