phptypestype-hinting

How to resolve "must be an instance of string, string given" prior to PHP 7?


Here is my code:

function phpwtf(string $s) {
    echo "$s\n";
}
phpwtf("Type hinting is da bomb");

Which results in this error:

Catchable fatal error: Argument 1 passed to phpwtf() must be an instance of string, string given

It's more than a little Orwellian to see PHP recognize and reject the desired type in the same breath. There are five lights, damn it.

What is the equivalent of type hinting for strings in PHP? Bonus consideration to the answer that explains exactly what is going on here.


Solution

  • Prior to PHP 7 type hinting can only be used to force the types of objects and arrays. Scalar types was not type-hintable. In this case an object of the class string is expected, but you're giving it a (scalar) string. The error message may be funny, but it's not supposed to work to begin with. Given the dynamic typing system, this actually makes some sort of perverted sense.

    Your best bet is to upgrade the PHP version, because even PHP7 is long gone now.

    In case it's impossible, you can simply remove that typehint altogether.

    If you still want to check the parameter type, you can do it manually:

    function foo($string) {
        if (!is_string($string)) {
            throw new RuntimeException(
                'Argument must be of type string '.gettype($type).' given'
            );
        }
        ...
    }