Any way to specify optional parameter values in PHP?

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

    If this is used very often, just define a new specialized function :

    function person($firstName = 'john', $lastName = 'doe') {
        return $firstName . " " . $lastName;
    }
    
    function usualFirtNamedPerson($lastName = 'doe') {
        return person('john', $lastName);
    }
    
    print(usualFirtNamedPerson('smith')); --> john smith
    

    Note that you could also change the default value of $lastname in the process if you wish.

    When a new function is estimated overbloated, just call you function with all parameters. If you want to make it more clear, you can prestore your literals in fin named variable or use comments.

    $firstName = 'Zeno';
    $lastName = 'of Elea';
    print(person($firstName, $lastName));
    print(person(/* $firstName = */ 'Bertrand', /* $lastName = */ 'Russel'));
    

    Ok, this is not as short and elegant as person($lastName='Lennon'), but it seems you can't have it in PHP. And that's not the sexiest way to code it, with super metaprogramming trick or whatever, but what solution would you prefer to encounter in a maintenance process?

提交回复
热议问题