简体   繁体   English

你如何在 php 中创建可选参数?

[英]How do you create optional arguments in php?

In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter.在 PHP 手册中,为了显示带有可选参数的函数的语法,他们在每组相关可选参数周围使用括号。 For example, for the date() function, the manual reads:例如,对于date()函数,手册上写着:

string date ( string $format [, int $timestamp = time() ] )

Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value.其中$timestamp是一个可选参数,当留空时它默认为time()函数的返回值。

How do you go about creating optional parameters like this when defining a custom function in PHP?在 PHP 中定义自定义函数时,您如何创建这样的可选参数?

Much like the manual, use an equals ( = ) sign in your definition of the parameters: 与手册非常相似,在参数定义中使用等号( = ):

function dosomething($var1, $var2, $var3 = 'somevalue'){
    // Rest of function here...
}

The default value of the argument must be a constant expression. 参数的默认值必须是常量表达式。 It can't be a variable or a function call. 它不能是变量或函数调用。

If you need this functionality however: 但是,如果您需要此功能:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course. 假设$bar当然不是布尔值。

Some notes that I also found useful: 我发现有用的一些注意事项:

  • Keep your default values on the right side. 保持默认值在右侧。

     function whatever($var1, $var2, $var3="constant", $var4="another") 
  • The default value of the argument must be a constant expression. 参数的默认值必须是常量表达式。 It can't be a variable or a function call. 它不能是变量或函数调用。

Give the optional argument a default value. 为可选参数指定默认值。

function date ($format, $timestamp='') {
}

The date function would be defined something like this: 日期函数将定义如下:

function date($format, $timestamp = null)
{
    if ($timestamp === null) {
        $timestamp = time();
    }

    // Format the timestamp according to $format
}

Usually, you would put the default value like this: 通常,您会将默认值设置为:

function foo($required, $optional = 42)
{
    // This function can be passed one or more arguments
}

However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time() , and combined it with a null check. 但是,只有文字是有效的默认参数,这就是为什么我在第一个例子中使用null作为默认参数, 而不是 $timestamp = time() ,并将其与空检查结合起来。 Literals include arrays ( array() or [] ), booleans, numbers, strings, and null . 文字包括数组( array()[] ),布尔值,数字,字符串和null

If you don't know how many attributes need to be processed, you can use the variadic argument list token( ... ) introduced in PHP 5.6 ( see full documentation here ). 如果您不知道需要处理多少属性,可以使用PHP 5.6中引入的variadic参数列表标记( ... )( 请参阅此处的完整文档 )。

Syntax: 句法:

function <functionName> ([<type> ]...<$paramName>) {}

For example: 例如:

function someVariadricFunc(...$arguments) {
  foreach ($arguments as $arg) {
    // do some stuff with $arg...
  }
}

someVariadricFunc();           // an empty array going to be passed
someVariadricFunc('apple');    // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');

As you can see, this token basically turns all parameters to an array, which you can process in any way you like. 如您所见,此令牌基本上将所有参数转换为数组,您可以以您喜欢的任何方式处理该数组。

Starting with 7.1 there is a type hinting for nullable parameters从 7.1 开始,有一个可空参数的类型提示

function func(?Object $object) {}

It will work for these cases:它将适用于这些情况:

func(null); //as nullable parameter
func(new Object());  // as parameter of declared  type

But for optional value signature should look like.但是对于可选值签名应该是这样的。

function func(Object $object = null) {} // In case of objects
function func(?Object $object = null) {} // or the same with nullable parameter

function func(string $object = '') {} // In case of scalar type - string, with string value as default value
function func(string $object = null) {} // In case of scalar type - string, with null as default value
function func(?string $object = '') {} // or the same with nullable parameter

function func(int $object = 0) {} // In case of scalar type - integer, with integer value as default value
function func(int $object = null) {} // In case of scalar type - integer, with null as default value
function func(?int $object = 0) {} // or the same with nullable parameter

than it can be invoked as比它可以调用为

func(); // as optional parameter
func(null); // as nullable parameter
func(new Object()); // as parameter of declared type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM