What is php type hinting?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Type hinting is a concept that provides hints to function for the expected data type of arguments.

    For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter. While calling the function we need to provide an argument of integer type only. If you provide data of any other type, it will throw an error with clear instructions that the value of an integer type is needed.

    Advantages of type hinting:

    • Type hinting helps users debug the code easily or the code provides errors very specifically.
    • It is a great concept for static kind of programming/data.

    Disadvantages of type hinting:

    • Functions only take one type of data.
    • The dynamicity of data or argument is not there.

    Example 1: In the following example, $var1 of type “cls” class is passed to the display() function. It displays the text of the class “cls”.

    PHP

      class cls{

          public $sentence="Hi welcome to php world";

      }

      function display(cls $var1){

          echo $var1->sentence;

      }

      display(new cls());

    ?>

    Output:

    Hi welcome to php world

    Example 2: The following example shows that $numbers is passed as a parameter to the add() function which is of type array. All the array items are added using the PHP foreach() loop.

    PHP

      function add(array $numbers){

          $sum=0;

          foreach($numbers as $item){

              $sum=$sum+$item;

          }

          echo $sum;

      }

      add(array(10,10));

    ?>

    Output:

    20

    If an integer is passed, the following error is thrown.

    What is php type hinting?


    Summary: in this tutorial, you’ll learn how to use PHP type hints to declare the types for function parameters and return values.

    Introduction to PHP type hints

    PHP is a dynamically typed language. When you define a function, you don’t need to declare types for parameters. For example:

    function add($x, $y) { return $x + $y; } $result = add(1,2); echo $result; // 3

    Code language: PHP (php)

    The add() function accepts two arguments and returns the sum of them. In this example, we pass two integers into the add() function and get the result as an integer.

    If you pass two floating-point numbers into the add() function, you’ll get the sum of the floats, which is a floating-point number:

    function add($x, $y) { return $x + $y; } $result = add(1.0,2.5); echo $result; // 3.5

    Code language: PHP (php)

    More interestingly, you can pass an integer and a numeric string into the add() function, it will return an integer:

    function add($x, $y) { return $x + $y; } $result = add(1,'2'); echo $result; // 3

    Code language: PHP (php)

    In this case, the add() function implicitly coerces the numeric string '2' into the integer 2 because of the + operator. If PHP fails to coerce the string argument into an integer, it’ll issue an error. For example:

    function add($x, $y) { return $x + $y; } $result = add('Hi','There'); echo $result;

    Code language: PHP (php)

    Error:

    Fatal error: Uncaught TypeError: Unsupported operand types: string + string in ...

    Code language: PHP (php)

    To enforce the types for function parameters and return value, you can use type hints.

    Note that PHP also allows you to use type hints for class properties and methods which you’ll learn in the PHP object-oriented programming tutorial.

    PHP type hints for function parameters

    The type hints ensure that PHP will check the type of a value at the call time and throw a TypeError if there is a mismatch.

    To add a type hint to a parameter, you place a type in front of it like this:

    function my_function(type $param1, type param2, ...) { // ... }

    Code language: PHP (php)

    In PHP 5, you can use array, callable, and class for type hints. In PHP 7+, you can also use scalar types such as bool, float, int, and string.

    The following defines the add() function that accepts two integers:

    function add(int $x, int $y) { return $x + $y; } $result = add(1,2); echo $result; // 3

    Code language: PHP (php)

    However, if you pass two floats, you’ll get the result as an integer:

    function add(int $x, int $y) { return $x + $y; } $result = add(1,2.5); echo $result; // 3

    Code language: PHP (php)

    In this case, PHP implicitly coerces 2.5 into an integer (2) before calculating the sum. Therefore, the result is an integer.

    By default, PHP coerces a value of the compatible type into the expected scalar type declaration if possible. To enforce the value with a type that matches the type declaration, you need to declare strict typing.

    PHP type hints for function’s return value

    To specify a return value’s type for a function, you add the type after the function header like this:

    function my_function(type $param1, type $param2, ...) : type { // .. }

    Code language: PHP (php)

    The following example defines the add() function that accepts two integers and returns an integer:

    function add(int $x, int $y): int { return $x + $y; } echo add(10, 20);

    Code language: PHP (php)

    Starting from PHP 7.0, if a function doesn’t return a value, you use the void type. For example:

    function dd($data):void { echo '

    ';
        var_dump($data);
        echo '
    '; die; }

    Code language: PHP (php)

    The union type

    Starting from PHP 8.0, if a function returns a value of several types, you can declare it as a union type. For example:

    function add($x, $y): int | float { return $x * $y; } echo add(10, 20); // 200 (int) echo add(1.5, 2.5); // 3.75 (float)

    Code language: PHP (php)

    In this example, the add() function returns an integer or a floating-point number, depending on the types of arguments.

    The mixed type

    If a function returns a value of many types, you can use the mixed type. The mixed type means one of several types. The mixed type. It’s equivalent to the following union type:

    object|resource|array|string|int|float|bool|null

    Code language: PHP (php)

    The mixed has been available since PHP 8.0.0.

    For example, the filter_var() built-in function use both union type (array|int) and mixed type as the type hints:

    filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed

    Code language: PHP (php)

    The nullable type

    The following defines a function that accepts a string and returns the uppercase of that string:

    function upper(string $str): string { return strtoupper($str); }

    Code language: HTML, XML (xml)

    If you pass an argument with null, you’ll get an error:

    function upper(string $str): string { return strtoupper($str); } $str = null; echo upper($str);

    Code language: HTML, XML (xml)

    Error:

    Fatal error: Uncaught TypeError: Argument 1 passed to upper() must be of the type string, null given

    Code language: plaintext (plaintext)

    To fix this, you can make the $str parameter nullable like this:

    function upper(?string $str): string { return strtoupper($str); } $str = null; echo upper($str);

    Code language: HTML, XML (xml)

    The nullable type was introduced in PHP 7.1.

    PHP allows you to mark the type declarations and returns values as nullable by prefixing the type name with a question mark (?).

    In the above example, we add the ? to the string type of the $str parameter. The ?string allows you to pass a string argument or null.

    Note that the mixed type already includes the null type. Therefore, you don’t need to include nullable mixed like this:

    ? mixed

    Also, doing so will result in an error.

    Summary

    • Use PHP type hints for function parameters and return types.
    • Use void type if the function doesn’t return any value.
    • Use mixed type or union type if function parameter or function return value expect on of several types.
    • To make a type nullable, prefix the type with a question mark (?type).

    Did you find this tutorial useful?

    What are type hints?

    Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.

    When was type hinting added PHP?

    In May of 2010 support for scalar type hinting was added to the PHP trunk.

    Does PHP have type safety?

    By this definition, PHP will never be type safe (PHP's compiler hardly prohibits any type errors). But that definition also isn't particularly useful to the majority of developers.

    What is type declaration also known as type hinting?

    Type declarations As of PHP 7 Type hinting is being referred to as Type declaration. PHP allows the developer to be more specific about what functions are getting and returning. You can optionally specify the type of parameters that the function needs and the type of result the function will return.