PHP scalar type and return value type declaration


Scalar type declaration

By default, all PHP files are in weak type checking mode.

PHP 7 adds the feature of scalar type declaration. There are two modes for scalar type declaration:

  • Forced mode (default)
  • Strict mode

Scalar type declaration syntax format:

declare(strict_types=1);

The value of strict_types (1 or 0) is specified in the code. 1 indicates strict type checking mode, which applies to function calls and return statements; 0 indicates weak Type checking mode.

The type parameters that can be used are:

  • #int

  • ##float

  • bool

  • string

  • interfaces

  • array

  • callable

Force mode example

Instance

<?php 
// 强制模式 
function sum(int ...$ints) 
{ 
   return array_sum($ints); 
} 

print(sum(2, '3', 4.1)); 
?>

The output result of the above program execution is:

9

Instance summary Convert parameter 4.1 to an integer 4 and then add it.

Strict Mode Example

Example

<?php 
// 严格模式 
declare(strict_types=1); 

function sum(int ...$ints) 
{ 
   return array_sum($ints); 
} 

print(sum(2, '3', 4.1)); 
?>

The above program uses strict mode, so if there is an inappropriate integer type in the parameter, an error will be reported, execute The output result is:

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


Return type declaration

PHP 7 adds support for return type declaration, which specifies the type of function return value.

The return types that can be declared are:

  • #int

  • ##float
  • bool
  • string
  • interfaces
  • array
  • callable
  • Return type declaration instance

In the instance, the return result is required to be an integer:

Instance
<?php
declare(strict_types=1);

function returnIntValue(int $value): int
{
   return $value;
}

print(returnIntValue(5));
?>

The execution output result of the above program is:
5

Return type declaration error example

Example
<?php
declare(strict_types=1);

function returnIntValue(int $value): int
{
   return $value + 1.0;
}

print(returnIntValue(5));
?>

The above program uses strict mode, the return value must be int, but the calculation result is float, so an error will be reported, and the execution output result is:
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...

Continuing Learning
||
<?php // 强制模式 function sum(int ...$ints) { return array_sum($ints); } print(sum(2, '3', 4.1)); ?>
submitReset Code