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

leepowers picture leepowers · Nov 5, 2010 · Viewed 105.7k times · Source

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.

Answer

deceze picture deceze · Nov 5, 2010

Prior to PHP 7 type hinting can only be used to force the types of objects and arrays. Scalar types are 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.

You can only manually "type hint" scalar types:

function foo($string) {
    if (!is_string($string)) {
        trigger_error('No, you fool!');
        return;
    }
    ...
}