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 code specifies the value of strict_types (1 or 0), 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
Example
The execution output of the above program is: <?php
// 强制模式
function sum(int ...$ints)
{
return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
9
Instance summary Convert parameter 4.1 into an integer 4 and then add it. Strict Mode ExampleExample
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
// 严格模式
declare(strict_types=1);
function sum(int ...$ints)
{
return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
PHP Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in……
Return type declarationPHP 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 of the above program is:
Return type declaration error example
Example<?php declare(strict_types=1); function returnIntValue(int $value): int { return $value + 1.0; } print(returnIntValue(5)); ?>Since the above program adopts strict mode, the return value must be int, but the calculation result is float, so an error will be reported. The execution output result is: