PHP VERSION: 8.2.18

type_hinting.php

<?php
// shows basic type hinting for scalars
declare(strict_types=1);

function 
add(float $afloat $b)
{
    return 
$a $b;
}

// works OK
var_dump(add(1.52.5));

// php 5.x ... works but gives NOTICE
// php 7 == Type Error
try {
    
var_dump(add('1 FOO''2'));
} catch (
TypeError $e) {
    echo 
'ERROR: ' $e->getMessage() . PHP_EOL;
}
// uses "widening"
var_dump(add(12));


Output


float(4)
ERROR: add(): Argument #1 ($a) must be of type float, string given, called in /homepages/22/d414837955/htdocs/repo/php7_examples/type_hinting.php on line 16
float(3)
SOURCE CODE