为什么类型转换不是PHP函数参数中的一个选项

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了为什么类型转换不是PHP函数参数中的一个选项脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
对于你们许多人来说这听起来像是一个愚蠢的问题,但它让我想知道为什么 PHP不允许在其函数参数中进行类型转换.许多人使用此方法来转换为他们的参数:
PRivate function dummy($id,$string){
    echo (int)$id." ".(string)$string
}

要么

private function dummy($id,$string){
    $number=(int)$id;
    $name=(string)$string;
    echo $number." ".$name;
}

但是看看许多其他编程语言,他们接受类型转换为他们的函数参数.但是在PHP中执行此操作可能会导致错误.

private function dummy((int)$id,(string)$string){
    echo $id." ".$string;
}

要么

private function dummy(intval($id),strval($string)){
    echo $id." ".$string;
}

只是想知道为什么这不起作用,如果有办法.如果没有办法,那么按照常规方式对我来说没问题:

private function dummy($id,$string){
    echo (int)$id." ".(string)$string;
}
PHP确实有一个 rudimentary type-hinting ability用于数组和对象,但它不适用于标量类型.

数组提示示例:

public function needs_array(array $arr) {
    var_dump($arr);
}

对象提示示例

public function needs_myClass(myClass $obj) {
    VAR_dump($obj);
}

如果需要强制执行标量类型,则需要通过类型转换或检查函数中的类型以及如果收到错误类型而挽救或采取相应行动.

如果输入错误,则抛出异常

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');
   }
}

只是地对params进行类型化

public function needs_int_and_string($int,$str) {
   $int = intval($int);
   $str = strval($str);
}

更新:PHP 7添加标量类型提示

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

脚本宝典总结

以上是脚本宝典为你收集整理的为什么类型转换不是PHP函数参数中的一个选项全部内容,希望文章能够帮你解决为什么类型转换不是PHP函数参数中的一个选项所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。