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

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

其中$timestamp是可选参数,当为空时,它默认为time()函数的返回值。

在PHP中定义自定义函数时,如何创建这样的可选参数?


当前回答

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
}

然而,只有文字是有效的默认参数,这就是为什么我在第一个例子中使用null作为默认参数,而不是$timestamp = time(),并将其与null检查结合起来。字面量包括数组(array()或[])、布尔值、数字、字符串和null。

其他回答

参数的默认值必须是常量表达式。它不能是变量或函数调用。

如果你需要这个功能:

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

当然,假设$bar不是一个布尔值。

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
}

然而,只有文字是有效的默认参数,这就是为什么我在第一个例子中使用null作为默认参数,而不是$timestamp = time(),并将其与null检查结合起来。字面量包括数组(array()或[])、布尔值、数字、字符串和null。

下面是一些我觉得很有用的笔记:

保持默认值在右侧。 函数($var1, $var2, $var3="常量",$var4="另一个") 参数的默认值必须是常量表达式。它不能是变量或函数调用。

给可选参数一个默认值。

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

很像手册,在你的参数定义中使用等号(=):

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