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

pieyvz9o  于 2023-01-08  发布在  PHP
关注(0)|答案(7)|浏览(117)

在PHP手册中,为了显示带有可选参数的函数的语法,他们在每一组依赖的可选参数周围使用括号。例如,对于date()函数,手册中写道:

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

其中$timestamp是可选参数,如果留空,则默认为time()函数的返回值。
在PHP中定义自定义函数时,如何创建这样的可选参数?

2hh7jdfx

2hh7jdfx1#

如果不知道需要处理多少属性,可以使用PHP 5.6中引入的变量参数列表标记(...)(请参阅此处的完整文档)。
语法:

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

例如:

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');

正如您所看到的,这个标记基本上将所有参数转换为一个数组,您可以按照自己喜欢的任何方式处理它。

oxf4rvwz

oxf4rvwz2#

从7.1开始,有一个类型提示可为空的参数

function func(?Object $object) {}

它适用于以下情况:

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

但对于可选值签名,应如下所示。

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

它可以被调用为

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

fgw7neuy3#

与手册非常相似,在参数定义中使用等号(=):

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

ny6fqffe4#

参数的默认值必须是常量表达式。它不能是变量或函数调用。
但是,如果您需要此功能:

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

当然,假设$bar不应该是布尔值。

zkure5ic

zkure5ic5#

我也发现了一些有用的注解:

  • 将默认值保留在右侧。
function whatever($var1, $var2, $var3="constant", $var4="another")
  • 参数的默认值必须是常量表达式。它不能是变量或函数调用。
xoefb8l8

xoefb8l86#

为可选参数指定默认值。

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

js4nwp547#

date函数的定义如下:

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

    // Format the timestamp according to $format
}

通常,您会将默认值设置为:

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

然而,只有 * literal * 才是有效的默认参数,这就是为什么我在第一个例子中使用null作为默认参数,而不是$timestamp = time(),并将其与null检查结合起来。

相关问题