Any way to specify optional parameter values in PHP?

后端 未结 12 903
谎友^
谎友^ 2020-11-28 06:54

Let\'s say I\'ve got a PHP function foo:

function foo($firstName = \'john\', $lastName = \'doe\') {
    echo $firstName . \" \" . $lastName;
}
// foo(); --&g         


        
12条回答
  •  醉酒成梦
    2020-11-28 07:09

    A variation on the array technique that allows for easier setting of default values:

    function foo($arguments) {
      $defaults = array(
        'firstName' => 'john',
        'lastName' => 'doe',
      );
    
      $arguments = array_merge($defaults, $arguments);
    
      echo $arguments['firstName'] . ' ' . $arguments['lastName'];
    }
    

    Usage:

    foo(array('lastName' => 'smith')); // output: john smith
    

提交回复
热议问题