In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date()
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. Literals include arrays (array()
or []
), booleans, numbers, strings, and null
.
Much like the manual, use an equals (=
) sign in your definition of the parameters:
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
Give the optional argument a default value.
function date ($format, $timestamp='') {
}
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.
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).
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.
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.