PHP 函数的字符串类型声明接受整数
PHP function's string type declaration accepts integers
我预计以下会产生类型错误,因为 123
是一个整数而不是一个字符串,所以可以为需要字符串的函数提供一个整数吗?
foo(123);
function foo(string $str) {
...
}
是的,因为整数可以转换为字符串(例如,数组不能)。
是的,除非你声明 declare(strict_types=1)
.
foo(123);
function foo(string $str) {
var_dump($str); // string(3) "123"
}
但以下内容:
declare(strict_types=1);
function foo(string $str) { }
foo(123); // FAIL (Uncaught TypeError)
将抛出:
Fatal error: Uncaught TypeError: foo(): Argument #1 ($str) must be of type string, int given
PHP manual 对此行为非常具体,并直接说明了您提出的示例:
By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.
这是否“OK”(如您所问)在很大程度上取决于实现。
我预计以下会产生类型错误,因为 123
是一个整数而不是一个字符串,所以可以为需要字符串的函数提供一个整数吗?
foo(123);
function foo(string $str) {
...
}
是的,因为整数可以转换为字符串(例如,数组不能)。
是的,除非你声明 declare(strict_types=1)
.
foo(123);
function foo(string $str) {
var_dump($str); // string(3) "123"
}
但以下内容:
declare(strict_types=1);
function foo(string $str) { }
foo(123); // FAIL (Uncaught TypeError)
将抛出:
Fatal error: Uncaught TypeError: foo(): Argument #1 ($str) must be of type string, int given
PHP manual 对此行为非常具体,并直接说明了您提出的示例:
By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.
这是否“OK”(如您所问)在很大程度上取决于实现。