【问题标题】:Call function with different arguments type in php在php中调用具有不同参数类型的函数
【发布时间】:2017-02-15 13:52:25
【问题描述】:

我需要构建一个方法column,它可以用不同的参数类型调用,比如这里的情况。

         ->column('herald','style')
         ->column('herald','style','styleText')
         ->column('herald',['kind','style'])
         ->column('herald',['kind','style'],['kindText','styleText'])
         ->column('item',['kind','style'],false)
         ->column('item',['kind','style'],['kindText','styleText'],false)
         ->column('herald_style','style',false)
         ->column('herald_style','style','styleText',false)

我只是希望函数可以被清楚地调用,像Java那样覆盖,我已经尝试使用func_get_args()来处理参数,但它似乎更糟糕..
那有什么办法吗?

【问题讨论】:

  • 您可以在函数参数中指定一个默认值,例如 function coloumn($a=null,&b=null,$c=null,$d=null){}
  • 你说的参数是什么意思 - ['kind','style']?
  • 我认为他希望参数可能是一个数组。@SanjayKumarNS
  • @Pradyut Manna 是的,我也这么认为。
  • @Fan,你能详细解释一下你想做什么吗?这种方法似乎不是最好的方法。 column() 做什么?

标签: php function laravel arguments


【解决方案1】:

在函数中接受可变数量的参数?

如果使用 PHP 5.6+,您可以使用 splat 运算符 ... 将任何提交的参数放入数组中。

function column(...$args) {

   // this is how many arguments were submitted
   $number_of_arguments = count($args);

   // iterate through them if you want...
   foreach($args as $arg) {

      // ...and process the arguments one by one
      do_something_with($arg);
   }
}

参见http://php.net/manual/en/functions.arguments.php 上的示例 13

如果使用早期版本的 PHP,那么 Sanjay Kumar N S 的答案就可以了。

【讨论】:

    【解决方案2】:

    如果你的意思是 ['kind','style'] 作为一个数组,那么试试这个:

    <?php
    function column()
    {
        $numargs = func_num_args();
        $arg_list = func_get_args();
        for ($i = 0; $i < $numargs; $i++) {
            echo "Argument $i is: " . (!is_array($arg_list[$i]) ? $arg_list[$i]: ' an array ' ). "<br />";
        }
        echo "<br /><br />";
    }
    
    column('herald','style');
    column('herald','style');
    column('herald','style','styleText');
    column('herald',array('kind','style'));
    column('herald',array('kind','style'),array('kindText','styleText'));
    column('item',array('kind','style'),false);
    column('item',array('kind','style'),array('kindText','styleText'),false);
    column('herald_style','style',false);
    column('herald_style','style','styleText',false);
    
    ?>
    

    【讨论】:

      【解决方案3】:

      您可以像这样在函数体中使用func_get_args()

      function callMe() {
          dd(func_get_args());
      } 
      

      另外,如果它取决于参数的数量,您可以使用 func_num_args()

      http://php.net/manual/ru/function.func-get-args.php

      【讨论】:

        猜你喜欢
        • 2020-02-20
        • 1970-01-01
        • 2020-01-23
        • 1970-01-01
        • 2011-11-13
        • 2019-12-31
        • 1970-01-01
        • 2016-11-05
        • 1970-01-01
        相关资源
        最近更新 更多