Alex Rivera | Logout

Any way to specify optional parameter values in PHP?

Asked 2009-03-27T17:00:00.483
24

Let's say I've got a PHP function foo:

function foo($firstName = 'john', $lastName = 'doe') {
    echo $firstName . " " . $lastName;
}
// foo(); --> john doe

Is there any way to specify only the second optional parameter?

Example:

foo($lastName='smith'); // output: john smith
Edit
Report

2 Answers

3

The way you want: no.

You could use some special mark, like NULL to note that value is not supplied:

function foo($firstName, $lastName = 'doe') {
    if (is_null($firstName))
        $firstName = 'john';
    echo $firstName . " " . $lastName;
}

foo(null, 'smith');
answered 2009-03-27T17:08:09.903
-1

No there isn't but you could use an array:

function foo ($nameArray) {
    // Work out which values are missing?
    echo $nameArray['firstName'] . " " . $nameArray['lastName'];
}

foo(array('lastName'=>'smith'));
answered 2009-03-27T17:09:55.607

Your Answer