PHP Type hinting scalar types, arrays and callables


Example

Support for type hinting array parameters (and return values after PHP 7.1) was added in PHP 5.1 with the keyword array. Any arrays of any dimensions and types, as well as empty arrays, are valid values.

Support for type hinting callables was added in PHP 5.4. Any value that is_callable() is valid for parameters and return values hinted callable, i.e. Closure objects, function name strings and array(class_name|object, method_name).

If a typo occurs in the function name such that it is not is_callable(), a less obvious error message would be displayed:

Fatal error: Uncaught TypeError: Argument 1 passed to foo() must be of the type callable, string/array given

function foo(callable $c) {}
foo("count"); // valid
foo("Phar::running"); // valid
foo(["Phar", "running"); // valid
foo([new ReflectionClass("stdClass"), "getName"]); // valid
foo(function() {}); // valid

foo("no_such_function"); // callable expected, string given

Nonstatic methods can also be passed as callables in static format, resulting in a deprecation warning and level E_STRICT error in PHP 7 and 5 respectively.

Method visibility is taken into account. If the context of the method with the callable parameter does not have access to the callable provided, it will end up as if the method does not exist.

class Foo{
  private static function f(){
    echo "Good" . PHP_EOL;
  }

  public static function r(callable $c){
    $c();
  }
}

function r(callable $c){}

Foo::r(["Foo", "f"]);
r(["Foo", "f"]);

Output:

Fatal error: Uncaught TypeError: Argument 1 passed to r() must be callable, array given

Support for type hinting scalar types was added in PHP 7. This means that we gain type hinting support for booleans, integers, floats and strings.

<?php

function add(int $a, int $b) {
    return $a + $b;
}

var_dump(add(1, 2)); // Outputs "int(3)"

By default, PHP will attempt to cast any provided argument to match its type hint. Changing the call to add(1.5, 2) gives exactly the same output, since the float 1.5 was cast to int by PHP.

To stop this behavior, one must add declare(strict_types=1); to the top of every PHP source file that requires it.

<?php

declare(strict_types=1);

function add(int $a, int $b) {
    return $a + $b;
}

var_dump(add(1.5, 2));

The above script now produces a fatal error:

Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, float given

An Exception: Special Types

Some PHP functions may return a value of type resource. Since this is not a scalar type, but a special type, it is not possible to type hint it.

As an example, curl_init() will return a resource, as well as fopen(). Of course, those two resources aren't compatible to each other. Because of that, PHP 7 will always throw the following TypeError when type hinting resource explicitly:

TypeError: Argument 1 passed to sample() must be an instance of resource, resource given