带可选参数的 PHP 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3978929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:37:48  来源:igfitidea点击:

PHP Function with Optional Parameters

phpfunctionparameter-passing

提问by user481826

I've written a PHP function that can accepts 10 parameters, but only 2 are required. Sometimes, I want to define the eighth parameter, but I don't want to type in empty strings for each of the parameters until I reach the eighth.

我写了一个 PHP 函数,可以接受 10 个参数,但只需要 2 个。有时,我想定义第八个参数,但我不想在到达第八个之前为每个参数输入空字符串。

One idea I had was to pass an abstracted function with an array of parameters which passes it along to the real function.

我的一个想法是传递一个带有参数数组的抽象函数,这些参数将其传递给真正的函数。

Is there a better way to set up the function so I can pass in only the parameters I want?

有没有更好的方法来设置函数,这样我就可以只传入我想要的参数?

采纳答案by Matt Ball

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.

使函数接受一个参数:一个数组。将实际参数作为数组中的值传入。



Edit:the link in Pekka's commentjust about sums it up.

编辑:Pekka 评论中的链接几乎总结了它。

回答by Rabbott

What I have done in this case is pass an array, where the key is the parameter name, and the value is the value.

我在这种情况下所做的是传递一个数组,其中键是参数名称,值是值。

$optional = array(
  "param" => $param1,
  "param2" => $param2
);

function func($required, $requiredTwo, $optional) {
  if(isset($optional["param2"])) {
    doWork();
  }
}

回答by Kayla Rose

To accomplish what you want, use an array Like Rabbot said(though this can become a pain to document/maintain if used excessively). Or just use the traditional optional args.

要完成您想要的操作,请使用Rabbot 所说的数组(尽管如果过度使用,这可能会成为记录/维护的痛苦)。或者只使用传统的可选参数。

//My function with tons of optional params
function my_func($req_a, $req_b, $opt_a = NULL, $opt_b = NULL, $opt_c = NULL)
{
  //Do stuff
}
my_func('Hi', 'World', null, null, 'Red');

However, I usually find that when I start writing a function/method with that many arguments - more often than not it is a code smell, and can be re-factored/abstracted into something much cleaner.

但是,我通常会发现,当我开始编写带有这么多参数的函数/方法时 - 通常是代码异味,并且可以重新分解/抽象为更清晰的东西。

//Specialization of my_func - assuming my_func itself cannot be refactored
function my_color_func($reg_a, $reg_b, $opt = 'Red')
{
  return my_func($reg_a, $reg_b, null, null, $opt);
}
my_color_func('Hi', 'World');
my_color_func('Hello', 'Universe', 'Green');

回答by Mentos1386

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

在 PHP 5.6 及更高版本中,参数列表可能包含 ... 标记以表示该函数接受可变数量的参数。参数将作为数组传递给给定的变量;例如:

Example Using ... to access variable arguments

示例使用 ... 访问变量参数

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

The above example will output:

上面的例子将输出:

10

Variable-length argument lists PHP Documentation

可变长度参数列表 PHP 文档

回答by Daniel Loureiro

NOTE: This is an old answer, for PHP 5.5and below. PHP 5.6+ supports default arguments

注意:这是一个旧答案,适用于PHP 5.5及更低版本。PHP 5.6+ 支持默认参数

In PHP 5.5 and below, you can achieve this by using one of these 2 methods:

在 PHP 5.5 及以下版本中,您可以使用以下两种方法之一来实现:

  • using the func_num_args()and func_get_arg()functions;
  • using NULL arguments;
  • 使用func_num_args()func_get_arg()函数;
  • 使用 NULL 参数;

How to use

如何使用

function method_1()
{
  $arg1 = (func_num_args() >= 1)? func_get_arg(0): "default_value_for_arg1";
  $arg2 = (func_num_args() >= 2)? func_get_arg(1): "default_value_for_arg2";
}

function method_2($arg1 = null, $arg2 = null)
{
  $arg1 = $arg1? $arg1: "default_value_for_arg1";
  $arg2 = $arg2? $arg2: "default_value_for_arg2";
}

I prefer the second method because it's clean and easy to understand, but sometimes you may need the first method.

我更喜欢第二种方法,因为它简洁易懂,但有时您可能需要第一种方法。

回答by Blake Stevenson

You can just set the default value to null.

您可以将默认值设置为 null。

<?php
function functionName($value, $value2 = null) {
// do stuff
}

回答by psad

I think, you can use objects as params-transportes, too.

我认为,您也可以将对象用作 params-transportes。

$myParam = new stdClass();
$myParam->optParam2 = 'something';
$myParam->optParam8 = 3;
theFunction($myParam);

function theFunction($fparam){      
  return "I got ".$fparam->optParam8." of ".$fparam->optParam2." received!";
}

Of course, you have to set default values for "optParam8" and "optParam2" in this function, in other case you will get "Notice: Undefined property: stdClass::$optParam2"

当然,你必须在这个函数中为“optParam8”和“optParam2”设置默认值,否则你会得到“Notice: Undefined property: stdClass::$optParam2”

If using arrays as function parameters, I like this way to set default values:

如果使用数组作为函数参数,我喜欢这种设置默认值的方式:

function theFunction($fparam){
   $default = array(
      'opt1' => 'nothing',
      'opt2' => 1
   );
   if(is_array($fparam)){
      $fparam = array_merge($default, $fparam);
   }else{
      $fparam = $default;
   }
   //now, the default values are overwritten by these passed by $fparam
   return "I received ".$fparam['opt1']." and ".$fparam['opt2']."!";
}

回答by Gordon

If only two values are required to create the object with a valid state, you could simply remove all the other optional arguments and provide setters for them (unless you dont want them to changed at runtime). Then just instantiate the object with the two required arguments and set the others as needed through the setter.

如果只需要两个值来创建具有有效状态的对象,您可以简单地删除所有其他可选参数并为它们提供设置器(除非您不希望它们在运行时更改)。然后只需使用两个必需的参数实例化对象,并根据需要通过 setter 设置其他参数。

Further reading

进一步阅读

回答by Chris

I know this is an old post, but i was having a problem like the OP and this is what i came up with.

我知道这是一篇旧帖子,但我遇到了像 OP 这样的问题,这就是我想出的。

Example of array you could pass. You could re order this if a particular order was required, but for this question this will do what is asked.

您可以传递的数组示例。如果需要特定订单,您可以重新订购,但对于这个问题,这将按照要求进行。

$argument_set = array (8 => 'lots', 5 => 'of', 1 => 'data', 2 => 'here');

This is manageable, easy to read and the data extraction points can be added and removed at a moments notice anywhere in coding and still avoid a massive rewrite. I used integer keys to tally with the OP original question but string keys could be used just as easily. In fact for readability I would advise it.

这是可管理的、易于阅读的,并且可以在编码中的任何地方随时添加和删除数据提取点,并且仍然避免大量重写。我使用整数键来解决 OP 原始问题,但可以轻松使用字符串键。事实上,为了可读性,我会建议它。

Stick this in an external file for ease

把它放在一个外部文件中以方便

function unknown_number_arguments($argument_set) {

    foreach ($argument_set as $key => $value) {

        # create a switch with all the cases you need. as you loop the array 
        # keys only your submitted $keys values will be found with the switch. 
        switch ($key) {
            case 1:
                # do stuff with $value
                break;
            case 2:
                # do stuff with $value;
                break;
            case 3:
                # key 3 omitted, this wont execute 
                break;
            case 5:
                # do stuff with $value;
                break;
            case 8:
                # do stuff with $value;
                break;
            default:
                # no match from the array, do error logging?
                break;
        }
    }
return;
}

put this at the start if the file.

把它放在开头,如果文件。

$argument_set = array(); 

Just use these to assign the next piece of data use numbering/naming according to where the data is coming from.

只需使用这些来分配下一条数据,根据数据的来源使用编号/命名。

$argument_set[1][] = $some_variable; 

And finally pass the array

最后传递数组

unknown_number_arguments($argument_set);

回答by antoine serry

function yourFunction($var1, $var2, $optional = Null){
   ... code
}

You can make a regular function and then add your optional variables by giving them a default Null value.

您可以创建一个常规函数,然后通过给它们一个默认的 Null 值来添加您的可选变量。

A Null is still a value, if you don't call the function with a value for that variable, it won't be empty so no error.

Null 仍然是一个值,如果您不使用该变量的值调用该函数,则它不会为空,因此不会出错。