PHP VERSION: 8.2.18
scalar_type_hints.php
<?php
declare(strict_types=1);
function add(float $a, float $b): float {
return $a + $b;
}
// The one exception is that widening primitive conversion is allowed for int to float.
// This means that parameters that declare float can also accept int.
var_dump(add(1, 2)); // float(3)
function test(int $i, float $f, string $s, bool $b): array {
return [$i, $f, $s, $b];
}
// works OK
var_dump(test(1, 22/7, 'TEST', TRUE));
// throws error
try {
var_dump(test('TEST', TRUE, 1, 22/7));
} catch (Error $e) {
echo 'ERROR: ' . $e;
}
Output
float(3)
array(4) {
[0]=>
int(1)
[1]=>
float(3.142857142857143)
[2]=>
string(4) "TEST"
[3]=>
bool(true)
}
ERROR: TypeError: test(): Argument #1 ($i) must be of type int, string given, called in /homepages/22/d414837955/htdocs/repo/php7_examples/scalar_type_hints.php on line 21 and defined in /homepages/22/d414837955/htdocs/repo/php7_examples/scalar_type_hints.php:12
Stack trace:
#0 /homepages/22/d414837955/htdocs/repo/php7_examples/scalar_type_hints.php(21): test()
#1 /homepages/22/d414837955/htdocs/php7/process.php(14): include('/homepages/22/d...')
#2 {main}
SOURCE CODE