Any way to specify optional parameter values in PHP?

后端 未结 12 884
谎友^
谎友^ 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:25

    If you have multiple optional parameters, one solution is to pass a single parameter that is a hash-array:

    function foo(array $params = array()) {
        $firstName = array_key_exists("firstName", $params) ?
          $params["firstName"] : "";
        $lastName = array_key_exists("lastName", $params) ?
          $params["lastName"] : "";
        echo $firstName . " " . $lastName;
    }
    
    foo(['lastName'=>'smith']);
    

    Of course in this solution there's no validation that the fields of the hash array are present, or spelled correctly. It's all up to you to validate.

提交回复
热议问题