【问题标题】:Does PHP have "named parameters" so that early arguments can be omitted and later arguments can be written? [duplicate]PHP 是否具有“命名参数”以便可以省略早期参数而可以编写后面的参数? [复制]
【发布时间】:2010-12-09 21:29:27
【问题描述】:

在 PHP 中,只要参数具有如下默认值,您就可以调用不带参数的函数:

function test($t1 ='test1',$t2 ='test2',$t3 ='test3')
{
    echo "$t1, $t2, $t3";
}
test();

但是,假设我希望最后一个参数不同,但前两个参数应该使用它们的默认值。我能想到的唯一方法是这样做没有成功:

test('test1','test2','hi i am different');

我试过这个:

test(,,'hi i am different');
test(default,default,'hi i am different');

有没有干净、有效的方法来做到这一点?

【问题讨论】:

标签: php named-parameters default-arguments php-8


【解决方案1】:

在 PHP 中,默认值的参数必须在最后,在其他参数之后,在调用函数时必须填写所有其他参数。反正我不知道要传递一个触发默认值的值。

【讨论】:

    【解决方案2】:

    使用数组:

    function test($options = array()) {
        $defaults = array(
            't1' => 'test1',
            't2' => 'test2',
            't3' => 'test3',
        );
        $options = array_merge($defauts, $options);
        extract($options);
        echo "$t1, $t2, $t3";
    }
    

    这样调用你的函数:

    test(array('t3' => 'hi, i am different'));
    

    【讨论】:

    • Peh,打败我。作为一个例子,extract 很好,但对于现实世界的使用,没有必要声明那么多变量。只是想注意;)
    【解决方案3】:

    在这些情况下,我通常所做的是将参数指定为数组。请看以下示例(未经测试):

    <?php
    test(array('t3' => 'something'));
    
    function test($options = array())
    {
      $default_options = array('t1' => 'test1', 't2' => 'test2', 't3' => 'test3');
      $options = array_merge($default_options, $options);
    
      echo $options['t1'] . ', ' . $options['t2'] . ', ' . $options['t3'];
    }
    ?>
    

    【讨论】:

      【解决方案4】:

      使用原始 PHP 无法做到这一点。您可以尝试以下方法:

      function test($var1 = null, $var2 = null){
          if($var1 == null) $var1 = 'default1';
          if($var2 == null) $var2 = 'default2';
      }
      

      然后调用你的函数,使用null作为默认变量的标识符。您还可以使用具有默认值的数组,使用更大的参数列表会更容易。

      更好的是尽量避免这一切,并重新考虑你的设计。

      【讨论】:

        【解决方案5】:

        你可以这样定义函数:

        function grafico($valores,$img_width=false,$img_height=false,$titulo="title"){
            if ($img_width===false){$img_width=450;}
            if ($img_height===false){$img_height=300;}
            ...
           }
        

        并在没有持久参数的情况下调用它或 用“false”替换一个或多个:

        grafico($values);
        grafico($values,300);
        grafico($values,false,400);
        grafico($values,false,400,"titleeee");
        

        【讨论】:

          猜你喜欢
          • 2022-01-23
          • 2014-03-21
          • 2013-10-08
          • 2018-11-06
          • 1970-01-01
          • 1970-01-01
          • 2020-01-10
          • 2011-02-08
          • 2021-12-26
          相关资源
          最近更新 更多