PHP Function with Optional Parameters

前端 未结 14 1142
星月不相逢
星月不相逢 2020-12-02 08:05

I\'ve written a PHP function that can accepts 10 parameters, but only 2 are required. Sometimes, I want to define the eighth parameter, but I don\'t want to type in empty st

相关标签:
14条回答
  • 2020-12-02 08:36
    function yourFunction($var1, $var2, $optional = Null){
       ... code
    }
    

    You can make a regular function and then add your optional variables by giving them a default Null value.

    A Null is still a value, if you don't call the function with a value for that variable, it won't be empty so no error.

    0 讨论(0)
  • 2020-12-02 08:38

    In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

    Example Using ... to access variable arguments

    <?php
    function sum(...$numbers) {
        $acc = 0;
        foreach ($numbers as $n) {
            $acc += $n;
        }
        return $acc;
    }
    
    echo sum(1, 2, 3, 4);
    ?>
    

    The above example will output:

    10
    

    Variable-length argument lists PHP Documentation

    0 讨论(0)
提交回复
热议问题