PHP VERSION: 7.0.26

scalar_type_hints.php

<?php
declare(strict_types=1);
 
function 
add(float $afloat $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(12)); // float(3)

function test(int $ifloat $fstring $sbool $b): array {
    return [
$i$f$s$b];
}

// works OK
var_dump(test(122/7'TEST'TRUE));

// throws error
try {
    
var_dump(test('TEST'TRUE122/7));
} catch (
Error $e) {
    echo 
'ERROR: ' $e;
}

 

Output


float(3)
array(4) {
  [0]=>
  int(1)
  [1]=>
  float(3.1428571428571)
  [2]=>
  string(4) "TEST"
  [3]=>
  bool(true)
}
ERROR: TypeError: Argument 1 passed to test() must be of the type integer, 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('TEST', true, 1, 3.1428571428571)
#1 /homepages/22/d414837955/htdocs/php7/process.php(14): include('/homepages/22/d...')
#2 {main}
SOURCE CODE