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

后端 未结 9 1264
情话喂你
情话喂你 2020-11-27 10:32

Here is my code:

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

Which results in this error:

9条回答
  •  囚心锁ツ
    2020-11-27 11:23

    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;
        }
        ...
    }
    

提交回复
热议问题