How to use strict types with union types (multiple types) in PHP

1 Answer

0 votes
declare(strict_types=1);

function formatId(int|string $id): string {
    return "ID: " . $id;
}

echo formatId(123) . "\n";     // OK
echo formatId("123") . "\n";   // OK
echo formatId(8921.4);   // TypeError



/*
run:

ERROR!
ID: 123
ID: 123

Fatal error: Uncaught TypeError: formatId(): Argument #1 ($id) must be of type string|int, float given

*/

 



answered Aug 9 by avibootz
...