Summary

This RFC proposes the addition of four type hints for scalar types: int, float, string and bool. These type hints would have “weak” type-checking by default, following the same casting rules traditionally used for the parameters of extension and built-in PHP functions.

This RFC further proposes the addition of a new optional per-file directive, declare(strict_types=1), which makes all function calls and return statements within a file have “strict” type-checking for scalar type hints, including for extension and built-in PHP functions. In addition, calls to extension and built-in PHP functions with this directive produce an E_RECOVERABLE_ERROR on parameter parsing failure, bringing them into line with userland type hints.

With these two features, it is hoped that more correct and self-documenting PHP programs can be written.

Example

Let's say we have a PHP class that represents an ElePHPant. We put scalar type hints on our constructor arguments:

However, there is a key difference between parameter and return type hints. The type-checking mode used for parameters is the one used by the file containing the function call, while the type-checking mode used for return values is the one used by the file containing the return statement (i.e. the file defining the function). So:

<?phpdeclare(strict_types=1){function foobar3(): int {return1.0;// error, regardless of where it is called from}
foobar3();// error}
foobar3();// also error

Background and Rationale

History

PHP has had parameter type hints for interface and class names since PHP 5.0, arrays since PHP 5.1 and callables since PHP 5.4. These type hints allow the PHP runtime to ensure that correctly-typed arguments are passed to functions, and make function signatures more informative. Unfortunately, PHP's scalar types haven't been hintable.

There have been some previous attempts at adding scalar type hints, such as the Scalar Type Hints with CastsRFC. From what I can see, that specific RFC failed primarily for three reasons:

Its type conversion and validation behaviour did not match that of extension and built-in PHP functions

It followed a weak typing approach

Its attempt at “stricter” weak typing failed to placate either strict typing or weak typing fans

In creating this RFC, I have attempted to learn from these failings.

Weak typing and strict typing

There are two major approaches to how to check parameter and return type hints that have been proposed for PHP:

Strict type checking, which is used by many popular programming languages, particularly ones which are statically-typed, such as Java, C#, Haskell, or Facebook's Hack. It is also used for non-scalar parameter type hints in PHP. With this approach, an argument is only accepted if its type is exactly the same as the parameter. So, for example, an integer is accepted for an integer parameter, but a float is not accepted. Such systems often also accept subclasses, so if Bar inherits from Foo, it might be accepted for a Foo parameter.

Weak type checking (which implicitly converts arguments, where possible, to the correct type), which is used to a limited extent by C, and is also the approach by PHP's extension and built-in functions for scalar types. With this approach, along with values with exactly matching types, some values that can be converted are accepted. So, for example, an integer is accepted for an integer parameter, but a float or a numeric string might also be accepted, depending on the rules of the language. These convertible values will be converted when they are passed to the function. So, even though the float value 1.0 might have been passed, the value the function actually gets is an integer 1.

Both approaches have their advantages and disadvantages, and in fact PHP already has a mix of both. We use strict type checking for non-scalars such as arrays, objects and resources, and this applies to both userland type hints, and extension and built-in PHP function parameter types. We use weak type checking for scalar parameter types, but only for extension and built-in PHP functions, as PHP does not currently have scalar type hints.

In both approaches, the function will always get exactly the argument type it asks for. In the case of strict type-checking, this is done by rejecting incorrectly-typed values. In the case of weak type-checking, this is done by rejecting some values, and converting others. Therefore, the following code will always work, regardless of mode:

function foobar(int $i){if(!is_int($i)){thrownew Exception("Not an integer.");// this will never happen}}

Similarly, in both approaches, a function will always return exactly the return type it claims to:

function barfoo(): int {/* ... */}if(!is_int(barfoo())){thrownew Exception("Not an integer.");// this will also never happen}

Why both?

So far, most advocates of scalar type hints have asked for either strict type checking, or weak type checking. Rather than picking one approach or the other, this RFC instead makes weak type checking the default, and adds an optional directive to use strict type checking within a file. There were several reasons behind this choice.

By and large the PHP community, myself included, seems to be in favour of strict type checking. However, adding strictly type-checked scalar type hints would cause a few problems:

The significant population who would like weak type checking would not be in favour of such a proposal, and are likely to block it.

Existing code which (perhaps unintentionally) took advantage of PHP's weak typing would break if functions it calls added scalar type hints to parameters. This would complicate the addition of scalar type hints to the parameters of functions in existing codebases, particularly libraries.

There is also a significant group of people (including, at times, my past self) who are in favour of weak type checking. But, like adding strictly type-checked hints, adding weakly type-checked scalar type hints would also cause problems:

The large number of people who would like strict type checking would not be in favour of such a proposal, and are likely to block it.

It would limit opportunities for static analysis.

A third approach has also been suggested, which is to add separate weakly- and strictly-checked type hints with different syntax. It would present its own set of issues:

People who do not like weak or strict type checking would be forced to deal with strictly or weakly type-checked libraries, respectively.

Like adding strict hints, this would also be inconsistent with extension and built-in PHP functions, which are uniformly weak.

In order to avoid the issues with these three approaches, this RFC proposes a fourth approach: per-file strict or weak type-checking. This has the following advantages:

People can choose the type checking model that suits them best, which means this approach should hopefully place both the strict and weak type checking camps.

APIs do not force a type hinting model upon their users.

Because files use the weak type checking approach by default, functions in existing codebases (including libraries) should be able to have scalar type hints added without breaking code that calls them. This enables codebases to add type hints gradually, or only to portions, which is known as “gradual typing”.

There only needs to be a single syntax for scalar type hints.

People who would prefer strict type checking get it not only for userland functions, but also for extension and built-in PHP functions. This means users get one model uniformly, rather than having the inconsistency that introducing strict-only scalar hints would have produced.

In strict type checking mode, the error level produced when type checking fails for extension and built-in PHP functions will finally be consistent with the error level produced for userland functions, with both producing E_RECOVERABLE_ERROR.

Type hint choices

No type hint for resources is added, as this would prevent moving from resources to objects for existing extensions, which some have already done (e.g. GMP).

For the integer typehint, both the int and integer syntaxes are allowed, and for the boolean typehint, both bool and boolean are allowed. This has been done because PHP uses both throughout the manual and error messages, so there is no clear choice of syntax that wouldn't cause problems. While in an ideal world we would not need to support these aliases, the likelihood of people being caught out by integer or boolean not working is very high, so I feel we ought to support both the short and long forms of these type names.

Details

Scalar type hints

No new reserved words are added. The names int, integer, float, string, bool and boolean are recognised and allowed as type hints, and prohibited from use as class/interface/trait names (including with use and class_alias).

strict_types declare() directive

By default, all PHP files are in weak type-checking mode. A new declare() directive is added, strict_types, which takes either 1 or 0. If 1, strict type-checking mode is used for function calls and return statements in the remainder of the file. If 0, weak type-checking mode is used.

This directive also supports the declare() block syntax (e.g. declare(strict_types=1) { foo(); }), in which case it will only affect function calls and return statements within the block.

Like the encoding directive, but unlike the ticks directive, the strict_types directive only affects the specific file it is used in, and does not affect either other files which include the file, nor other files that are included by the file.

The directive is entirely compile-time and cannot be controlled at runtime. It works by setting a flag on the opcodes for function calls (for parameter type hints) and return type checks (for return type hints).

Parameter type hints

The directive affects any function call, including those within a function or method. For example:

Unlike parameter type hints, the type checking mode used for return types depends on the file where the function is defined, not where the function is called. This is because returning the wrong type is a problem with the callee, while passing the wrong type is a problem with the caller.

Behaviour of weak type checks

A weakly type-checked call to an extension or built-in PHP function has exactly the same behaviour as it did in previous PHP versions.

The weak type checking rules for the new scalar type hints are mostly the same as those of extension and built-in PHP functions. The only exception to this is the handling of NULL: in order to be consistent with our existing type hints for classes, callables and arrays, NULL is not accepted by default, unless it is a parameter and is explicitly given a default value of NULL. This would work well with the draft Declaring Nullable TypesRFC. If that RFC were to pass, it would be possible to mark return types as nullable, and so they would accept NULL.

For the reference of readers who may not be familiar with PHP's existing weak scalar parameter type rules, the following brief summary is provided.

The table shows which types are accepted and converted for scalar type hints. NULL, arrays and resources are never accepted for scalar type hints, and so are not included in the table.

Type hint

integer

float

string

boolean

object

integer

yes

yes*

yes†

yes

no

float

yes

yes

yes†

yes

no

string

yes

yes

yes

yes

yes‡

boolean

yes

yes

yes

yes

no

*Only non-NaN floats between PHP_INT_MIN and PHP_INT_MAX accepted. (New in PHP 7, see the ZPP Failure on OverflowRFC)

†Non-numeric strings not accepted. Numeric strings with trailing characters are accepted, but produce a notice.

‡Only if it has a __toString method.

Behaviour of strict type checks

A strictly type-checked call to an extension or built-in PHP function changes the behaviour of zend_parse_parameters. In particular, it will produce E_RECOVERABLE_ERROR rather than E_WARNING on failure, and it follows strict type checking rules for scalar typed parameters, rather than the traditional weak type checking rules.

The strict type checking rules are quite straightforward: when the type of the value matches that specified by the type hint it is accepted, otherwise it is not.

These strict type checking rules are used for userland scalar type hints, and for extension and built-in PHP functions.

Backward Incompatible Changes

int, integer, float, string, bool and boolean are no longer permitted as class/interface/trait names (including with use and class_alias).

Because the weak type-checking rules for scalar hints are quite permissive in the values they accept and behave similarly to PHP's type juggling for operators, it should be possible for existing userland libraries to add scalar type hints without breaking compatibility.

Since the strict type-checking mode is off by default and must be explicitly used, it does not break backwards-compatibility.

Proposed PHP Version(s)

This is proposed for the next PHP x, currently PHP 7.

RFC Impact

To Existing Extensions

ext/reflection will need to be updated in order to support scalar type hint reflection for parameters. This hasn't yet been done.

Unaffected PHP Functionality

This doesn't affect the behaviour of cast operators.

When the strict type-checking mode isn't in use (which is the default), function calls to built-in and extension PHP functions behave identically to previous PHP versions.

Open Issues

There is currently an open issue related to naming, described below. This will go to a vote.

This RFC and patch allows the aliases integer and boolean in addition to int and bool. Should we only allow int and bool? It is probably not a good idea to add too many new reserved class names. On the other hand, we use integer and boolean in many places in the manual, and programmers would be forgiven for expecting integer and boolean to work. We could opt to reserve them but prevent their use, telling people to use int and bool instead. That wouldn't reduce the number of prohibited class names, but it would prevent confusion and ensure consistency.

TODO

Produce a different error message on strict type hint failure vs. on weak type hint failure, lest debugging be a pain. For practical reasons we may not be able to change the weak one, as it is an existing message (should we?).

Return types need more tests.

Future Scope

Because scalar type hints guarantee that a passed argument will be of a certain type within a function body (at least initially), this could be used in the Zend Engine for optimisations. For example, if a function takes two float-hinted arguments and does arithmetic with them, there is no need for the arithmetic operators to check the types of their operands. As I understand it, HHVM already does such optimisations, and might benefit from this RFC.

In discussions around this RFC, the declare(strict_types=1); syntax has been controversial. It is arguably rather ugly, and it has all the scoping quirks of declare(). I've now arrived at a point where I'm willing to change to a truly per-file syntax, <?php strict (or similar). However, the RFC is currently being voted on, and I'd rather not cancel the vote. So, this will be proposed in a subsequent RFC.

Another issue that came up is PHP's lack of a typehint for numbers (which also came up with the previous Scalar Type Hinting with Cast RFC). I plan to propose a numeric typehint in a future RFC which would take either an integer or a float.

Vote

As this is a language change, this RFC requires a 2/3 majority to pass. Voting for all three votes started on 2015-02-05 and all were to end on 2015-02-19, but the voting was cancelled and the RFC withdrawn on 2015-02-15.

Reserve for future use

This final vote is in case the RFC fails to pass. It's a 2/3 majority-required backwards compatibility-breaking language change, which is to reserve the type hint names proposed by the RFC, so that a future RFC could implement scalar type hints without requiring a backwards compatibility break. The type names reserved include the synonyms integer and boolean. They would not be reserved words, merely prohibited from use as class/interface/trait names, like this RFC's type names.