2024-01-03 20:00:00 +00:00
---
title: >
2024-02-07 20:01:19 +00:00
PHP types and assertions
2024-01-03 20:00:00 +00:00
pubDate: 2023-08-20
permalink: >-
2024-02-07 20:01:19 +00:00
archive/2023/08/20/php-types-and-assertions
2024-01-03 20:00:00 +00:00
tags:
2024-02-07 20:01:19 +00:00
- php
2024-01-03 20:00:00 +00:00
---
Following yesterday's email about input validation, guard clauses and assertion libraries, these can be used to compliment PHP's native types and checking.
For example:
2024-02-18 01:35:59 +00:00
```language-php
2024-01-03 20:00:00 +00:00
function createJourney(string $from, string $to, int $duration): void {
var_dump($from, $to, $duration);
}
```
In this code, each parameter has a type, but there's no validation on the values.
If I run this:
2024-02-18 01:35:59 +00:00
```language-plain
2024-01-03 20:00:00 +00:00
createJourney('', '', -10);
```
I would get this output:
2024-02-18 01:35:59 +00:00
```language-plain
2024-01-03 20:00:00 +00:00
string(0) ""
string(0) ""
int(-10)
```
This is probably not what you want.
I expect `$to` and `$from` to be not empty and the duration to be greater than zero.
## Here's the thing
I can use an assertion library or throw my own Exceptions if the values pass the type checks but aren't what I need.
For example:
2024-02-18 01:35:59 +00:00
```language-php
2024-01-03 20:00:00 +00:00
function createJourney(string $from, string $to, int $duration): void {
Assert::stringNotEmpty($from);
Assert::stringNotEmpty($to);
Assert::positiveInteger($duration);
var_dump($from, $to, $duration);
}
```
Now, if an empty string or negative duration is passed - in my implementation or test code - an Exception will be thrown.