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

With strict types enabled, array_map converts types anyways

我在 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 社区决定现在应该这样做的方式。