简体   繁体   English

如何检查 PHP function 参数值是否通过调用 function 设置或默认值

[英]How to check if PHP function parameter value set by calling function or default value

I want to check if PHP functions parameter value set by calling function or its a default value我想检查 PHP 函数参数值是否通过调用 function 或其默认值设置

function our_round($value,$decimal=6){
   if($decimal == 6 && $value < 0){
     $decimal = 9; // default
   }

   if($decimal == 6 && && value < 0 && provided by calling function){
     // need this logic to code here.
     // keep 6 if 6 provided by provider
     $decimal  = 6;
   }

   return round($value,$decimal);
}

// calling
our_round(1.1234567); // decimal default value
our_round(1.1234567,2); // decimal value provided 
our_round(1.1234567,6); // decimal value provided 

When calling function pass 6 in decimal, i want to check if its default or provided?当调用 function 以十进制传递 6 时,我想检查它是默认的还是提供的? to do some logic.做一些逻辑。

You can check what values were provided using func_get_args() .您可以使用func_get_args()检查提供了哪些值。 However, I have to agree with the comments that such an approach makes no sense.但是,我必须同意这种方法没有意义的评论。

function func($a = 2) {
    var_dump($a, func_get_args());
}
func();

func_get_args() only returns arguments which were passed in when calling the function, not set by default values. func_get_args()仅返回调用 function 时传入的 arguments,默认值未设置。

In your case, it would make more sense to make the second parameter nullable and then have the complex logic inside of the function's body.在您的情况下,使第二个参数可以为空,然后在函数体内包含复杂的逻辑会更有意义。

function our_round(float $value, ?int $decimal = null) {
    if (null === $decimal && $value < 0) {
        $decimal = 9; // default
    } else {
        // need this logic to code here.
        // keep 6 if 6 provided by provider
        $decimal = 6;
    }

    return round($value, $decimal);
}

I would recommend taking a piece of paper and drow some kind of truth table of possible options.我建议拿一张纸,画出一些可能选项的真值表。 If you just want to assign a default value in a simple way you can use a ternary operator.如果您只想以简单的方式分配默认值,则可以使用三元运算符。

function our_round(float $value, ?int $decimal = null) {
    // assign default value
    $decimal ??= $value < 0 ? 9 : 6;

    return round($value, $decimal);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM