問題描述
這是我的代碼:
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模板網!