PHP VERSION: 7.0.26

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: Argument 1 passed to add() must be of the type float, string given, called in /homepages/22/d414837955/htdocs/repo/php7_examples/type_hinting.php on line 16
float(3)
SOURCE CODE