PHP 7 Scalar Type Declarations

Scalar type declarations has been introduced in PHP 7.

Scalar type declaration has following two option.

  • Coercive: coercive is default type declaration.
  • Strict: In strict strict mode, a single declare directive must be placed at the top of the file.Strictness of typing for scalars is configured on a per-file basis.

The function parameters can be enforced using the following modes.

  • strings
  • float
  • int
  • bool
  • interfaces
  • callable
  • array

Coercive Mode Example in PHP 7

<?php
// Coercive mode
function sum(int ...$ints) {
return array_sum($ints);
}
print(sum(4, '2', 4.1));
?>

OutPut

The above example will output: 10

Strict Mode Example in PHP 7

<?php
declare(strict_types=1); // Strict mode
function sum(int ...$ints) {
return array_sum($ints);
}
print(sum(4, '2', 4.1));
?>

OutPut

The above example will output: "PHP Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer".