Library contents

PHP TypeError

A strict integer parameter rejects an imported fare of the wrong type.

A simple example

TypeError

  1. Start with Text "2" where an integer is required
  2. Do this Check or cast the type
  3. Result Type mismatch
A string containing a digit is still a string. Parsing would be a separate operation.

Syntax

PHP 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.php

Check 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.

From the programdeclare(strict_types=1)
ResultReview fare type
lesson.php
<?php
declare(strict_types=1);
function receiptFare(int $cents): int {
    return $cents;
}
try {
    echo receiptFare('free');
} catch (TypeError $wrongType) {
    echo 'Review fare type';
}
Output
Review fare type

The imported value holds text. The desk flags the fare before treating it as a number.

Advertisements

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.

GivenInteger 36
Worked resultNumber accepted

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.

GivenText “36”
Worked resultReview field type

What to watch for

Strict scalar checking is selected by the calling file. Put declare(strict_types=1) before other statements.

Documentation for TypeError