PHP ??? ?? ? ?? ? ?? ??
??? ?? ??
????? ?? PHP ??? ?? ?? ?? ?????.
PHP 7?? ??? ?? ?? ??? ???????. ??? ?? ???? ? ?? ??? ????:
- Force ??(???)
- Strict ??
??? ?? ?? ?? ??:
declare(strict_types=1);
?? ?(1 ?? 0), 1? ?? ?? ? ?? ?? ???? ??? ?? ?? ??? ?????. 0? ?? ?? ?? ??? ?????.
?? ??? ?? ????? ??? ????:
int
float
bool
string
interfaces
-
??
?? ??
force mode ??
Example
<?php // 強(qiáng)制模式 function sum(int ...$ints) { return array_sum($ints); } print(sum(2, '3', 4.1)); ?>
? ???? ?? ?? ??? ??? ????.
9
?? ?? ???? 4.1? ?? 4? ??? ? ?????.
?? ?? ??
Instance
<?php // 嚴(yán)格模式 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……
?? ?? ?????.
PHP 7 ?? ?? ?? ?? ?? ??? ?? ?? ??? ?? ?? ?? ??? ?????.
??? ? ?? ?? ??? ??? ????:
int
float
bool
string
interfaces
-
??
?? ??
?? ?? ?? ????
?????? ?? ??? ???? ???.
????
<?php declare(strict_types=1); function returnIntValue(int $value): int { return $value; } print(returnIntValue(5)); ?>
? ???? ?? ?? ??? ??? ????.
5
?? ?? ?? ?? ????
????
<?php declare(strict_types=1); function returnIntValue(int $value): int { return $value + 1.0; } print(returnIntValue(5)); ?>
? ????? ?? ??? ???? ?? ?? int?? ??? ?? ??? float??? ?? ?? ???
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...