在 PHP 函数中传递可选参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5441894/
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 21:26:04  来源:igfitidea点击:

Passing an optional parameter in PHP Function

php

提问by Peter

How can I pass an optional parameter to a PHP function. For example

如何将可选参数传递给 PHP 函数。例如

function test($required, $optional){..}

So that i should be able to call the function by passing either one parameter or both. For example:

这样我就可以通过传递一个或两个参数来调用该函数。例如:

test($required, $optional)
test($required);

Thanks.

谢谢。

回答by felixsigl

try this:

尝试这个:

function test($required, $optional = NULL){..} 

then you can call

然后你可以打电话

test($required, $optional)

and with $optionalnull

$optional

test($required);  

回答by Skilldrick

With a default value:

使用默认值

function test($required, $optional="default value"){..}

回答by Alp

1) You can define default values for arguments like so:

1)您可以为参数定义默认值,如下所示:

function test($required, $optional = false) {}

2) You can use func_num_args()to get the number of arguments, func_get_arg($n)to get the n'th argument or func_get_args()to get an array of all arguments.

2) 您可以使用func_num_args()获取参数的数量,使用func_get_arg($n)获取第 n 个参数或使用func_get_args()获取所有参数的数组。

You can find a good summary here: Function arguments

你可以在这里找到一个很好的总结:函数参数

回答by Limon

You can also do this:

你也可以这样做:

function test($required, $optional = ''){
    #code
}

when calling:

打电话时:

test($required)

or:

或者:

test($required, $optional = 'something')

回答by mjspier

just set the default parameters in your function ex.

只需在您的函数中设置默认参数即可。

function test($required, $optional = null, ... )

now you can call your function like this

现在你可以像这样调用你的函数

test($required, $optional)
test($required);

回答by diEcho

read this http://php.net/manual/en/function.func-get-args.php

阅读这个http://php.net/manual/en/function.func-get-args.php

dont pass any argument when decalare a function like below

在 decalare 像下面这样的函数时不要传递任何参数

function myMin() {
      $list = func_get_args();
      $min = NULL;
      if (count($list)>0) $min = $list[0];
      for ($i=1; $i<count($list); $i++) {
         if ($min > $list[$i]) $min = $list[$i];
      }
      return $min;
   }

   print("\n Calling a function that uses func_get_args():\n");
   print("    ".myMin()."\n");
   print("    ".myMin(5)."\n");
   print("    ".myMin(5, 6, 2)."\n");
   print("    ".myMin(5, 6, 2, 9, 5, 1, 4, 1, 3)."\n");
?>