在PHP7中,键入提示对函数中的字符串不起作用
对于字符串,类型提示不起作用在PHP7中,键入提示对函数中的字符串不起作用,php,string,function,types,hints,Php,String,Function,Types,Hints,对于字符串,类型提示不起作用 function def_arg(int $name, int $address, string $test){ return $name . $address . $test; } echo def_arg(3, 4, 10) ; // It doesn't throws an error as expected. 另一方面。若您在第一个参数中给出字符串,它会抛出一个错误,指出它应该是int function def_arg(int $name, i
function def_arg(int $name, int $address, string $test){
return $name . $address . $test;
}
echo def_arg(3, 4, 10) ;
// It doesn't throws an error as expected.
另一方面。若您在第一个参数中给出字符串,它会抛出一个错误,指出它应该是int
function def_arg(int $name, int $address, string $test){
return $name . $address . $test;
}
echo def_arg("any text", 4, "abc") ;
// this code throws an error
// "Fatal error: Uncaught TypeError: Argument 1 passed to def_arg() must be of the type integer, string given,"
为什么字符串没有错误???这是因为默认情况下,PHP会尽可能将错误类型的值强制转换为预期的标量类型。例如,为期望字符串的参数指定整数的函数将获得字符串类型的变量 看 如果您在第二个示例中使用可以强制转换的值,它将起作用:
function def_arg(int $name, int $address, string $test){
return $name . $address . $test;
}
echo def_arg("12", "22", 1) ;
这是因为这些值可以从string转换为int,反之亦然
可以基于每个文件启用严格模式。在严格模式下,只接受类型声明的确切类型的变量,或者抛出TypeError。此规则的唯一例外是,可能会给期望浮点的函数一个整数。来自内部函数的函数调用将不受严格类型声明的影响