php - 启用严格类型后,array_map 无论如何都会转换类型

标签 php types type-hinting

我在 PHP 7.0.11 中遇到了一个非常有趣的错误,其中启用 declare(strict_types=1); 不会使 array_map()array_walk() 了解严格类型。我在某处读到,通过启用严格类型,PHP 也在核心函数中使用了严格类型,但事实并非如此。 看这个示例代码,它应该抛出 TypeError 异常:

declare(strict_types=1);

$myArray = [12, 'string value', 'another string value', 5];

array_map('validateMyArrayValues', $myArray);

function validateMyArrayValues(string $item)
{
    var_dump($item);
}

var_dump 结果是:

test.php:13:
    string(2) "12"
test.php:13:
    string(12) "string value"
test.php:13:
    string(20) "another string value"
test.php:13:
    string(1) "5"

所有整数值都被类型转换为字符串,这显然是一个问题。这就提出了一个问题,我是否应该完全放弃 declare(strict_types=1); 并使用 is_* 函数并抛出异常?

最佳答案

这不是错误(向 Room 11 致敬,因为它为我指明了正确的方向)

这是 Strict Types RFC .它真的非常非常长,而且是 PHP 历史上最有争议的 RFC(我是认真的)。这是为您截取的相关部分

This proposal builds in weak type checking by default (using the same rules), for internal and user functions.

A significant portion of the PHP community appears to favor fully-strict types. However, adding strictly type-checked scalar type declarations would cause a few problems:

Existing code which (perhaps unintentionally) took advantage of PHP's weak typing would break if functions it calls added scalar type declarations to parameters. This would complicate the addition of scalar type declarations to the parameters of functions in existing codebases, particularly libraries.

所以这不是错误。这是使这成为可能的重大妥协的一部分(如果您愿意,可以朝着更严格的类型迈出一小步)。函数忽略严格类型。是的,它与其他语言不一致(RFC 详细说明了这一事实),但这就是 PHP 社区目前决定​​的方式。

关于php - 启用严格类型后,array_map 无论如何都会转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41472406/

相关文章:

java - 可以在 Java 中创建新的原始数据类型

python - 绕过 "typing.Union is not a generic class"

python - 如何在 python 3.6 中键入 hinte 高阶函数?

php - `yield from $generator` 和 `return $generator` 之间的区别?

php - "Personal Home Page"和 "PHP Hypertext Preprocessor"是什么 PHP?

scala - 是否有一种内置的更优雅的方式来按元素类型过滤和映射集合?

c# - 定义类型别名

python - isinstance 如何为 List 工作?

php - 合并三个表并用mysql统计一个特定的值

php - Javascript 爆炸和循环