How do you create optional arguments in php?

后端 未结 6 1644
耶瑟儿~
耶瑟儿~ 2020-11-27 02:54

In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date()

相关标签:
6条回答
  • 2020-11-27 03:30

    The date function would be defined something like this:

    function date($format, $timestamp = null)
    {
        if ($timestamp === null) {
            $timestamp = time();
        }
    
        // Format the timestamp according to $format
    }
    

    Usually, you would put the default value like this:

    function foo($required, $optional = 42)
    {
        // This function can be passed one or more arguments
    }
    

    However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time(), and combined it with a null check. Literals include arrays (array() or []), booleans, numbers, strings, and null.

    0 讨论(0)
  • 2020-11-27 03:31

    Much like the manual, use an equals (=) sign in your definition of the parameters:

    function dosomething($var1, $var2, $var3 = 'somevalue'){
        // Rest of function here...
    }
    
    0 讨论(0)
  • 2020-11-27 03:46

    Give the optional argument a default value.

    function date ($format, $timestamp='') {
    }
    
    0 讨论(0)
  • 2020-11-27 03:47

    Some notes that I also found useful:

    • Keep your default values on the right side.

      function whatever($var1, $var2, $var3="constant", $var4="another")
      
    • The default value of the argument must be a constant expression. It can't be a variable or a function call.

    0 讨论(0)
  • 2020-11-27 03:47

    If you don't know how many attributes need to be processed, you can use the variadic argument list token(...) introduced in PHP 5.6 (see full documentation here).

    Syntax:

    function <functionName> ([<type> ]...<$paramName>) {}
    

    For example:

    function someVariadricFunc(...$arguments) {
      foreach ($arguments as $arg) {
        // do some stuff with $arg...
      }
    }
    
    someVariadricFunc();           // an empty array going to be passed
    someVariadricFunc('apple');    // provides a one-element array
    someVariadricFunc('apple', 'pear', 'orange', 'banana');
    

    As you can see, this token basically turns all parameters to an array, which you can process in any way you like.

    0 讨论(0)
  • 2020-11-27 03:49

    The default value of the argument must be a constant expression. It can't be a variable or a function call.

    If you need this functionality however:

    function foo($foo, $bar = false)
    {
        if(!$bar)
        {
            $bar = $foo;
        }
    }
    

    Assuming $bar isn't expected to be a boolean of course.

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