Any way to specify optional parameter values in PHP?

后端 未结 12 904
谎友^
谎友^ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 07:18

    Sadly what you're trying to do has no "syntactic sugar" way of doing it. They're all varying forms of WTF.

    If you need a function that takes an undefined number of arbitrary parameters,

    function foo () { 
         $args = func_get_args(); 
         # $args = arguments in order 
    }
    

    Will do the trick. Try avoid using it too much, because for Php this is a bit on the magical side.

    You could then optionally apply defaults and do strange things based on parameter count.

    function foo(){ 
       $args = func_get_args();
       if( count($args) < 1 ){ 
           return "John Smith"; 
       }
       if( count($args) < 2 ) { 
           return "John " .$args[0];
       }
       return $args[0] . " " . $args[1];
    }
    

    Also, you could optionally emulate Perl style parameters,

    function params_collect( $arglist ){ 
        $config = array();
        for( $i = 0; $i < count($arglist); $i+=2 ){ 
           $config[$i] = $config[$i+1];
        }
        return $config; 
    }
    function param_default( $config, $param, $default ){ 
        if( !isset( $config[$param] ) ){ 
               $config[$param] = $default;
        }
        return $config;
    }
    
    function foo(){ 
       $args = func_get_args();
       $config = params_collect( $args ); 
       $config = param_default( $config, 'firstname' , 'John' ); 
       $config = param_default( $config, 'lastname' ,  'Smith' ); 
       return $config['firstname'] . '  ' . $config['lastname'];   
    }
    
    foo( 'firstname' , 'john', 'lastname' , 'bob' ); 
    foo( 'lastname' , 'bob', 'firstname', 'bob' ); 
    foo( 'firstname' , 'smith'); 
    foo( 'lastname', 'john' );
    

    Of course, it would be easier to use an array argument here, but you're permitted to have choice ( even bad ways ) of doing things.

    notedly, this is nicer in Perl because you can do just foo( firstname => 'john' );

    • func_get_args at php.net

提交回复
热议问题