这是我的代码:
function phpwtf(string $s) {
echo "$s
";
}
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 同时识别和拒绝所需的类型,这不仅仅是一点奥威尔式的.有五个灯,该死.
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 之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!