rfc:scalar_type_hints

This is an old revision of the document!


PHP RFC: Scalar Type Hints

  • Version: 0.2.3
  • Date: 2014-12-14 (initial draft; put Under Discussion 2014-12-31; version 0.2 created 2015-01-13)
  • Author: Andrea Faulds, ajf@ajf.me
  • Status: Under Discussion

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 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 within a file have “strict” type-checking for parameters with 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:

ElePHPant.php
<?php
class ElePHPant {
    public $name, $age, $cuteness, $evil;
    public function __construct(string $name, int $age, float $cuteness, bool $evil) {
        $this->name = $name;
        $this->age = $age;
        $this->cuteness = $cuteness;
        $this->evil = $evil;
    }
}

In a separate file we might try to make a new instance like so:

main.php
<?php
require "ElePHPant.php";
 
$sara = new ElePHPant("Sara", 7, 0.99, FALSE);
var_dump($sara); /*
object(ElePHPant)#1 (4) {
  ["name"]=>
  string(4) "Sara"
  ["age"]=>
  int(7)
  ["cuteness"]=>
  float(0.99)
  ["evil"]=>
  bool(false)
} */

This call succeeds, because the types of the arguments passed exactly match the type hints.

By default, weak type hints that permit some conversions are used, so we could also pass values that are convertible and they'll be converted, just like with extension and built-in PHP functions:

main2.php
<?php
require "ElePHPant.php";
 
$nelly = new ElePHPant(12345, "7 years", "0.9", "1");
var_dump($nelly); /*
object(ElePHPant)#2 (4) {
  ["name"]=>
  string(5) "12345"
  ["age"]=>
  int(7)
  ["cuteness"]=>
  float(0.9)
  ["evil"]=>
  bool(true)
}
Notice: A non well formed numeric value encountered
*/

However, it is also possible to turn on strict type checking with an optional directive. In this mode, the same call would fail:

main3.php
<?php
require "ElePHPant.php";
 
declare(strict_types=1);
 
$nelly = new ElePHPant(12345, "7 years", "0.9", "1");
// Catchable fatal error: Argument 1 passed to ElePHPant::__construct() must be of the type string, integer given

The strict type checking mode also affects extension and built-in PHP functions:

main4.php
<?php
 
declare(strict_types=1);
 
$foo = sin(1);
// Catchable fatal error: sin() expects parameter 1 to be float, integer given

Background and Rationale

History

PHP has had parameter type hints for 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 Casts RFC. 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 attempts to learn from these failings.

Weak typing and strict typing

There are two major approaches to how to check parameter types or 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)) {
        throw new Exception("Not an integer."); // this will 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:

  • It creates a glaring inconsistency: extension and built-in PHP functions use weak type checking for scalar typed parameters, yet userland PHP functions would be using strict type checking for scalar type hinted parameters.
  • 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).

The new userland scalar type hints are implemented internally by calling the Fast Parameter Parsing API functions.

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 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 made 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 affects any function call, including those within a function or method. For example:

strict_types_scope.php
<?php
 
declare(strict_types=1) {
    foo(); // strictly type-checked function call
 
    function foobar() {
        foo(); // strictly type-checked function call
    }
 
    class baz {
        function foobar() {
            foo(); // strictly type-checked function call
        }
    }
}
 
foo(); // weakly type-checked function call
 
function foobar() {
    foo(); // weakly type-checked function call
}
 
class baz {
    function foobar() {
        foo(); // weakly type-checked function call
    }
}

Whether or not the function being called was declared in a file that uses strict or weak type checking is entirely irrelevant. The type checking mode depends on the file where the function is called.

Behaviour of weakly type-checked function calls

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 the parameter is explicitly given a default value of NULL. This would work well with the draft Declaring Nullable Types RFC.

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

Behaviour of strictly type-checked function calls

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 passed argument matches that specified by the parameter 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 behave identically to previous PHP versions.

Open Issues

There are two open issues related to naming. These might be voted on if consensus isn't reached.

  • Currently, 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.
  • Should the scalar type hint names be prohibited from use as class names? The patch currently prohibits this (class int {} is an error), to avoid the situation where you can declare a class with the name of a scalar type hint yet not type hint against it (as the name would be interpreted as a scalar hint). Personally, I think it'd be best to avoid confusion and prevent classes from having the same names as scalar types. However, if this causes significant backwards-compatibility problems, we might have to allow it. I would note that at least some of the existing classes with such names are used as a stand-in for scalar type hints.
    • The patch doesn't currently do this, but it would make sense to also prevent scalar type hint names being used with the use statement.

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?).

Future Scope

If return types are added, such as with the Return Type Hinting RFC, scalar type hints should be supported. Unlike parameter types, it would probably not make sense to allow weak type-checking for return types. Allowing weak type-checking for parameter types, but only strict type-checking for return types, would be consistent with the principle of "be conservative in what you send, be liberal in what you accept". If we are to reject this principle and allow weak type-checking for return types, then the type-checking mode should depend on where the function is defined, rather than where it 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.

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.

Proposed Voting Choices

As this is a language change, this RFC requires a 2/3 majority to pass. It will be a Yes/No vote.

Patches and Tests

There is a working, but incomplete php-src pull request with tests here: https://github.com/php/php-src/pull/998

There is no language specification patch.

Implementation

After the project is implemented, this section should contain

  1. the version(s) it was merged to
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature

References

  • Previous discussions on the internals mailing list about scalar type hinting: one, two, three, four

Changelog

  • v0.2.3 - strict_types=1 rather than strict_typehints=TRUE
  • v0.2.2 - Follow robustness principle for return types under Future Scope
  • v0.2.1 - Weak typing clarification
  • v0.2 - Introduction of optional strict hinting mode
  • v0.1.2 - Noted some downsides of strict hints vs weak hints
  • v0.1.1 - Added table summarising casting and validation rules
  • v0.1 - Initial drafts
rfc/scalar_type_hints.1422158400.txt.gz · Last modified: 2017/09/22 13:28 (external edit)