PHP Scalar Type Declarations and Return Type Declarations
Scalar type declarations
By default, all PHP files are in weak type checking mode.
PHP 7 added the feature of scalar type declarations, which has two modes:
- Coercive mode (default)
- Strict mode
Scalar type declaration syntax format:
declare(strict_types=1);
In the code, by specifying the value of strict_types (1 or 0), 1 means strict type checking mode, which applies to function calls and return statements; 0 means weak type checking mode.
The type parameters that can be used are:
-
int
-
float
-
bool
-
string
-
interfaces
-
array
-
callable
Coercive mode example
Example
The output of the above program is:
9
The example converts the parameter 4.1 to the integer 4 before adding.
Strict mode example
Example
Since the above program uses strict mode, if a type that is not an integer appears in the parameters, an error will be reported. The execution output is:
PHP Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in……
Return type declarations
PHP 7 added support for return type declarations, which specify the type of a function's return value.
The return types that can be declared are:
-
int
-
float
-
bool
-
string
-
interfaces
-
array
-
callable
Return type declaration example
In the example, the return result is required to be an integer:
Example
The output of the above program is:
5
Return type declaration error example
Example
Since the above program uses strict mode, the return value must be int, but the calculation result is float, so an error will be reported. The execution output is:
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...
void functions
A new return value type void has been introduced. A method whose return value is declared as void must either omit the return statement entirely, or use an empty return statement. For void functions, NULL is not a valid return value.
The return type void is also available; a function declared with return type void cannot return a value, not even null.
A void function can omit the return statement, or use an empty return statement.
PHP 7 New Features