PHP - Function parameter and return type hinting


PHP 7 allows to specify type for what functions are getting and returning.

You can optionally specify the type of argument that the function needs (type hinting).

You can also set the type of result the function will return (return type).


    function addNumbers(int $a, int $b, bool $printSum): int { 
        $sum = $a + $b; 
        if ($printSum) { 
            echo 'The sum is ' . $sum; 
         return $sum; 

     addNumbers(1, 2, true); 
     addNumbers(1, '2', true); // it fails when strict_types is 1 
     addNumbers(1, 'something', true); // it always fails 

Here, the function states that the arguments need to be integer, integer, and Boolean, and that the result will be an integer.

Because of PHP type juggling, it can usually transform a value of one type to its equivalent value of another type, for example, the string "2" can be used as integer 2.

To stop PHP from using type juggling with the arguments and results of functions, you can declare the directive strict_types.

This directive has to be declared at the top of each file where you want to enforce this behavior.

The first invocation sends two integers and a Boolean, which is what the function expects, so regardless of the value of strict_types, it will always work.

The second invocation sends an integer, a string, and a Boolean. The string has a valid integer value, so if PHP was allowed to use type juggling, the invocation would resolve just normally. But in this example, it will fail because of the declaration at the top of the file.

The third invocation will always fail as the string "something" cannot be transformed into a valid integer.

Related Topic