如何解析“必须是字符串,给定的字符串的实例".在PHP 7之前? [英] How to resolve "must be an instance of string, string given" prior to PHP 7?

查看:101
本文介绍了如何解析“必须是字符串,给定的字符串的实例".在PHP 7之前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

哪个会导致此错误:

可捕获的致命错误:传递给phpwtf()的参数1必须是字符串的实例,给定的字符串

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

看到PHP同时识别并拒绝所需的类型,不仅仅需要一点点Orwellian. 该死的,有五个灯.

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.

PHP中字符串的类型提示等效于什么?对答案的额外考虑,可以准确解释这里发生的情况.

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

推荐答案

PHP 7之前的版本类型提示仅可用于强制对象和数组的类型.标量类型不是类型隐含的.在这种情况下,应该使用类string的对象,但是您要给它一个(标量)string.该错误消息可能很有趣,但是一开始它不起作用.在使用动态打字系统的情况下,这实际上具有某种变态的意义.

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

这篇关于如何解析“必须是字符串,给定的字符串的实例".在PHP 7之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆