Share via:

PHP: String Type not Working in Type Hinting

Why string type hinting still allows us to use integers as input, and how we can solve the problem.

61 views

Edited: 2019-12-17 08:50

I started using PHP7's type hinting some time ago, my understanding being that the input type of functions and methods would be validated automatically. But, it appears that the string type is not strictly validated, it is, however, if we use the str short-hand.

This is a serious problem, because people do not expect this behavior. I now got a lot of code that I need to update as a result.

The problem happens because PHP will attempt to use a value of the wrong type, as the expected scalar type when possible. This means that a function that only accepts a string will also accept an integer, unless we enable strict types. To enable strict type hinting, place the following at the top of a script:

declare(strict_types=1);

However, you may not want to clutter scripts with such unnecessary fiddling. Another option appears to be to use the str short-hand instead of string when declaring our input types.

To demonstrate the problem, I created a short class with a single method and tried using different type hints, such as int, string, array, and finally the working str short-hand.

This test is included below:

$pooper = new type_hint_test();
$poop = 44444;

echo $pooper->string_test($poop);
echo $pooper->str_test($poop);


class type_hint_test {

  public function string_test(string $poop) {
    echo $poop; // Passes, without validating the input type
  }
  public function str_test(str $poop) {
    echo $poop; // Correctly outputs a type error
  }

}

While the first test passes, the second will result in a type error like this:

Fatal error: Uncaught TypeError: Argument 1 passed to type_hint_test::str_test() must be an instance of str, int given...

Comments