PHP TypeError
A strict integer parameter rejects an imported fare of the wrong type.
A simple example
TypeError
- Start with Text "2" where an integer is required
- Do this Check or cast the type
- Result Type mismatch
Syntax
catch (TypeError $error)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpCheck the type of an imported fare
A transit app imports fares from two ticket machines. One machine sends the word “free” in a field normally filled with a whole number, so the importer needs to flag the record for review.
<?php
declare(strict_types=1);
function receiptFare(int $cents): int {
return $cents;
}
try {
echo receiptFare('free');
} catch (TypeError $wrongType) {
echo 'Review fare type';
}
Review fare type
The imported value holds text. The desk flags the fare before treating it as a number.
Import a museum headcount
The counter sends the number 36 as an integer object. The import expects an integer value. Flag a text field for review before calculating a total.
Review a quoted fare
A new terminal sends its fare as text in a field that previously carried an integer. The import expects an integer value. Flag a text field for review before calculating a total.
What to watch for
Strict scalar checking is selected by the calling file. Put declare(strict_types=1) before other statements.