Add daily email for 2024-05-04
Strict typing in PHP
This commit is contained in:
parent
e3b6a8feec
commit
d3789edb27
38
source/_daily_emails/2024-05-04.md
Normal file
38
source/_daily_emails/2024-05-04.md
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
---
|
||||||
|
title: Strict typing in PHP
|
||||||
|
date: 2024-05-04
|
||||||
|
permalink: archive/2024/05/04/strict-typing-in-php
|
||||||
|
tags:
|
||||||
|
- software-development
|
||||||
|
- php
|
||||||
|
cta: ~
|
||||||
|
snippet: |
|
||||||
|
Do you enable strict types in your PHP code?
|
||||||
|
---
|
||||||
|
|
||||||
|
I prefer writing and working with strictly typed code.
|
||||||
|
|
||||||
|
One of the major improvements in PHP has been the option to enable strict types.
|
||||||
|
|
||||||
|
For example, this code will usually not error and give the result:
|
||||||
|
|
||||||
|
```php
|
||||||
|
function add(int $a, int $b): void
|
||||||
|
{
|
||||||
|
var_dump($a + $b);
|
||||||
|
}
|
||||||
|
|
||||||
|
add(1, '1');
|
||||||
|
```
|
||||||
|
|
||||||
|
However, I'd prefer if it failed as I'm passing the function an integer and a string, but specifying they should both be integers.
|
||||||
|
|
||||||
|
Fixing this is simple, by adding this line to the top of the file:
|
||||||
|
|
||||||
|
```php
|
||||||
|
declare(strict_types=1);
|
||||||
|
```
|
||||||
|
|
||||||
|
I add this to every PHP file by default.
|
||||||
|
|
||||||
|
I want my code to be as strict and predictable as possible, and to error when I want it to and make any bugs more explicit and easier to find and fix.
|
Loading…
Reference in a new issue