PHP 类型提示被忽略,没有抛出 TypeError 异常 [英] PHP type hinting is being ignored, no TypeError exception is thrown
问题描述
我刚刚调试了一些 PHP 7.1 代码,其中我忘记删除对返回值的 (bool)
强制转换,但该函数的声明返回类型为 int
:
I just debugged some PHP 7.1 code where I'd forgotten to remove a (bool)
cast on the return value, but the function had a declared return type of int
:
function get_foo(): int {
$val = get_option('foo');
return (bool) $val;
}
$foo = get_foo();
在bool
和int
之间转换当然很容易,但是为什么这不抛出TypeError?
It's easy to cast between bool
and int
, of course, but why didn't this throw a TypeError?
在三种情况下可能会抛出 TypeError....第二种情况是从函数返回的值与声明的函数返回类型不匹配.
There are three scenarios where a TypeError may be thrown. ... The second is where a value being returned from a function does not match the declared function return type.
对于类型化的函数参数表现出相同的行为.
The same behaviour is exhibited for typed function parameters.
function get_foo(string $foo): int {
$val = get_option($foo);
return (bool) $val;
}
// no TypeError!
$foo = get_foo(34);
推荐答案
您需要添加 strict_types
指令,类型提示才能正常工作
You need to add the strict_types
directive for type hinting to work properly
引用自 PHP 7 新功能
要启用严格模式,必须在文件顶部放置一个声明指令.这意味着标量输入的严格性是在每个文件的基础上配置的.该指令不仅会影响参数的类型声明,还会影响函数的返回类型(请参阅返回类型声明、内置 PHP 函数和来自加载扩展的函数.
To enable strict mode, a single declare directive must be placed at the top of the file. This means that the strictness of typing for scalars is configured on a per-file basis. This directive not only affects the type declarations of parameters, but also a function's return type (see return type declarations, built-in PHP functions, and functions from loaded extensions.
有了这个,你应该这样做.
With that, you should do this.
<?php
declare(strict_types=1);
function get_option_foo() : int {
$val = get_option('foo'); // Returns a string that can be parsed as an int
return (bool) $val;
}
$foo = get_option_foo();
再试一次,你会收到一个Uncaught TypeError Exception
Try this once again, you will receive an Uncaught TypeError Exception
这篇关于PHP 类型提示被忽略,没有抛出 TypeError 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!