English 中文(简体)
PHP 7 - Scalar Type Declarations
  • 时间:2024-11-03

PHP 7 - Scalar Type Declarations


Previous Page Next Page  

In PHP 7, a new feature, Scalar type declarations, has been introduced. Scalar type declaration has two options −

    coercive − coercive is default mode and need not to be specified.

    strict − strict mode has to exppcitly hinted.

Following types for function parameters can be enforced using 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(2,  3 , 4.1));
?>

It produces the following browser output −

9

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, ...
Advertisements