WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML


 

PHP 7 Scalar Type Declarations




In PHP 7, another component, Scalar type announcements, has been presented. Scalar type declaration has two alternatives −

  • coercive - coercive is default mode and need not to be specified.

  • strict - exacting mode needs to expressly hinted.

Following types for function parameters can be implemented utilizing the above modes −

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable

Example - Coercive Mode

<?php
   // Coercive mode
   function sum(int ...$ints) {
      return array_sum($ints);
   }
   print(sum(3, '3', 4.1));
?>
It produces the following browser output −
10


Example - Strict Mode

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

It produces the following browser output −

Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, ...