对于你们许多人来说这听起来像是一个愚蠢的问题,但它让我想知道为什么
PHP不允许在其函数参数中进行类型转换.许多人使用此方法来转换为他们的参数:
private function dummy($id,$string){ echo (int)$id." ".(string)$string }@H_404_3@要么
private function dummy($id,$string){ $number=(int)$id; $name=(string)$string; echo $number." ".$name; }@H_404_3@但是看看许多其他编程语言,他们接受类型转换为他们的函数参数.但是在PHP中执行此操作可能会导致错误.
private function dummy((int)$id,(string)$string){ echo $id." ".$string; }
@H_404_3@Parse error: Syntax error,unexpected T_INT_CAST,expecting ‘&’ or T_VARIABLE @H_404_14@ @H_404_3@要么private function dummy(intval($id),strval($string)){ echo $id." ".$string; }@H_404_3@Parse error: Syntax error,unexpected ‘(‘,expecting ‘&’ or T_VARIABLE @H_404_14@ @H_404_3@只是想知道为什么这不起作用,如果有办法.如果没有办法,那么按照常规方式对我来说没问题:private function dummy($id,$string){ echo (int)$id." ".(string)$string; }
PHP确实有一个
rudimentary type-hinting ability用于数组和对象,但它不适用于标量类型.
@H_404_3@PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype),interfaces,arrays (since PHP 5.1) or callable (since PHP 5.4). However,if NULL is used as the default parameter value,it will be allowed as an argument for any later call. @H_404_3@If class or interface is specified as type hint then all its children or implementations are allow>ed too. @H_404_3@Type hints can not be used with scalar types such as int or string. Traits are not allowed either. @H_404_14@ @H_404_3@数组提示示例:public function needs_array(array $arr) { var_dump($arr); }@H_404_3@对象提示示例public function needs_myClass(myClass $obj) { var_dump($obj); }@H_404_3@如果需要强制执行标量类型,则需要通过类型转换或检查函数中的类型以及如果收到错误类型而挽救或采取相应行动. @H_404_3@如果输入错误,则抛出异常public function needs_int_and_string($int,$str) { if (!ctype_digit(strval($int)) { throw new Exception('$int must be an int'); } if (strval($str) !== $str) { throw new Exception('$str must be a string'); } }@H_404_3@只是默默地对params进行类型化public function needs_int_and_string($int,$str) { $int = intval($int); $str = strval($str); }@H_404_3@更新:PHP 7添加标量类型提示 @H_404_3@PHP 7引入了严格和非严格模式的Scalar type declarations.如果函数参数变量与声明的类型不完全匹配,或者以非严格模式强制类型,现在可以在严格模式下抛出TypeError.declare(strict_types=1); function int_only(int $i) { // echo $i; } $input_string = "123"; // string int_only($input); // TypeError: Argument 1 passed to int_only() must be of the type integer,string given