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

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

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

The execution output result of the above program is:
5

Return type declaration error example

Example

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
||
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!