rfc:basic_scalar_types

PHP RFC: Basic Scalar Types

Introduction

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.

Proposal

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.

simple.php
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.

return.php
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"

Backward Incompatible Changes

There is no other compatibility break apart from removing int, float, string and bool as class, interface or trait name.

Proposed PHP Version(s)

PHP 7.0

Future Scope

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.

Proposed Voting Choices

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?

  1. Yes
  2. No

The vote will require a 2/3 majority.

Patches and Tests

The patch is a variation of https://github.com/ircmaxell/php-src/compare/scalar_type_hints_v5 without the declare()/strict part.

Implementation

TBD

References

The other two RFCs aiming for scalar type hints:

  1. https://wiki.php.net/rfc/coercive_sth — Coercive types for function arguments
  2. https://wiki.php.net/rfc/scalar_type_hints_v5 — Scalar type declarations
rfc/basic_scalar_types.txt · Last modified: 2017/09/22 13:28 by 127.0.0.1