How do you create optional arguments in php?

php

Question

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() function, the manual reads:

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.

How do you go about creating optional parameters like this when defining a custom function in PHP?

1
171
7/3/2014 3:45:48 PM

Accepted Answer

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
    // Rest of function here...
}
235
7/3/2014 3:46:59 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon