对于你们许多人来说这听起来像是一个愚蠢的问题,但它让我想知道为什么PHP不允许在其函数参数中进行类型转换.许多人使用此方法来转换为他们的参数:
private function dummy($id,$string){
echo (int)$id." ".(string)$string
}
Run Code Online (Sandbox Code Playgroud)
要么
private function dummy($id,$string){
$number=(int)$id;
$name=(string)$string;
echo $number." ".$name;
}
Run Code Online (Sandbox Code Playgroud)
但是看看许多其他编程语言,他们接受类型转换为他们的函数参数.但是在PHP中执行此操作可能会导致错误.
private function dummy((int)$id,(string)$string){
echo $id." ".$string;
}
Run Code Online (Sandbox Code Playgroud)
解析错误:语法错误,意外T_INT_CAST,期待'&'或T_VARIABLE
要么
private function dummy(intval($id),strval($string)){
echo $id." ".$string;
}
Run Code Online (Sandbox Code Playgroud)
解析错误:语法错误,意外'(',期待'&'或T_VARIABLE
只是想知道为什么这不起作用,如果有办法.如果没有办法,那么按照常规方式对我来说没问题:
private function dummy($id,$string){
echo (int)$id." ".(string)$string;
}
Run Code Online (Sandbox Code Playgroud)