We already had multiple attempts at getting scalar types in PHP 7.0. With a series of withdrawn RFCs and two other votes going on currently whose outcome is not yet clear by a large margin.
Thus, this RFC tries to introduce a basic set of scalar types, in case the other RFCs trying to get them in fail, in order to have scalar types at all in PHP 7.0.
This RFC proposes a basic set of types: int
, float
, string
and bool
.
There are no new keywords added for them, they just will be prohibited from usage as class, interface and trait names (including any sort of aliasing).
They should behave just like they already do with current parameter parsing behavior of internal functions for scalars.
Which means:
Type declaration | int | float | string | bool | object | null | array |
---|---|---|---|---|---|---|---|
int | yes | yes* | yes† | yes | no | yes | no |
float | yes | yes | yes† | yes | no | yes | no |
string | yes | yes | yes | yes | yes‡ | yes | no |
bool | yes | yes | yes | yes | no | yes | no |
*Only non-NaN floats between PHP_INT_MIN
and PHP_INT_MAX
accepted. (New in PHP 7, see the ZPP Failure on Overflow RFC)
†Non-numeric strings not accepted. Numeric strings with trailing characters are accepted, but produce a notice.
‡Only if it has a __toString
method.
Typed parameters always will be casted to their respective type, if accepted.
function foo(int $param) { var_dump($param); // int(2) } foo(2); foo("2"); foo(2.3);
The scalar types can be also used as return types. The return value then will be appropriately casted, if accepted.
function foo($param): string { return $param . "baz"; } var_dump(foo(2)); // string(4) "2baz" var_dump(foo("2")); // string(4) "2baz" var_dump(foo(2.3)); // string(6) "2.3baz"
There is no other compatibility break apart from removing int
, float
, string
and bool
as class, interface or trait name.
PHP 7.0
The RFC only aims to introduce a very basic skeleton of scalar types.
Everything else can be built on top on it later. This RFC won't create any real hurdle for potential future improvements in later versions.
In case where all the RFCs trying to introduce scalar types into PHP 7.0 should fail the vote, should these four basic scalar types be introduced?
The vote will require a 2/3 majority.
The patch is a variation of https://github.com/ircmaxell/php-src/compare/scalar_type_hints_v5 without the declare()/strict part.
TBD
The other two RFCs aiming for scalar type hints: