PHP 类型提示被忽略,没有抛出 TypeError 异常

PHP type hinting is being ignored, no TypeError exception is thrown

我刚刚调试了一些 PHP 7.1 代码,其中我忘记删除 return 值上的 (bool) 强制转换,但该函数声明了 return int 的类型:

function get_foo(): int {
    $val = get_option('foo');
    return (bool) $val;
}

$foo = get_foo();

Test the code here.

当然,在 boolint 之间转换很容易,但是 为什么这没有抛出 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.

类型化函数参数表现出相同的行为。

function get_foo(string $foo): int {
    $val = get_option($foo);
    return (bool) $val;
}

// no TypeError!
$foo = get_foo(34);

您需要添加 strict_types 指令以使类型提示正常工作

引用自PHP 7 New Features

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.

有了这个,你应该这样做。

<?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