在 PHP 手册中,为了显示带有可选参数的函数的语法,它们在每组依赖的可选参数周围使用括号。例如,对于该date()
功能,手册中写道:
string date ( string $format [, int $timestamp = time() ] )
where$timestamp
是可选参数,留空时默认为time()
函数的返回值。
在 PHP 中定义自定义函数时,如何创建这样的可选参数?
=
与手册非常相似,在参数定义中使用等号 ( ) :
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
参数的默认值必须是常量表达式。它不能是变量或函数调用。
但是,如果您需要此功能:
function foo($foo, $bar = false)
{
if(!$bar)
{
$bar = $foo;
}
}
假设$bar
当然不会是布尔值。
我也发现一些有用的注释:
将默认值保留在右侧。
function whatever($var1, $var2, $var3="constant", $var4="another")
参数的默认值必须是常量表达式。它不能是变量或函数调用。
给可选参数一个默认值。
function date ($format, $timestamp='') {
}
日期函数将被定义为:
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
在第一个示例中使用not $timestamp = time()
作为默认参数,并将其与空检查结合使用。文字包括数组 ( array()
or []
)、布尔值、数字、字符串和null
.
如果您不知道需要处理多少个属性,可以使用...
PHP 5.6 中引入的可变参数列表 token()(请参阅此处的完整文档)。
句法:
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');
如您所见,此标记基本上将所有参数转换为一个数组,您可以以任何您喜欢的方式对其进行处理。
从 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