Forum Moderators: coopster

Message Too Old, No Replies

Function argument default to another argument

         

miketurpin

4:44 pm on Jan 20, 2011 (gmt 0)

10+ Year Member



Hi,

I'd need a function where an optional argument takes on the value of another argument when it's not specified. I'd like to be able to write:

function some_fun ($a, $b, $c, $d=$b) {
...

However, this is not correct PHP syntax. I'd really like it to be, and may suggest it as an enhancement.

Instead, as $d is a string I thought of doing a bit of a workaround like:

function some_fun ($a, $b, $c, $d='COPY $b') {
if ($d = 'COPY $b') {$d = $b;}
...

Not as elegant as having PHP language support, but it'll do for now.

Anyone else needed this?

miketurpin

5:13 pm on Jan 20, 2011 (gmt 0)

10+ Year Member



I posted this on another forum and the answer I liked best was:

function someFunction($a, $b, $c, $d = null)
{
//Set $d to $b if $d is not set
if( is_null($d) === true ){$d = $b;}
...
}

He also pointed out that I could simply call it with $b twice:

someFunction($a, $b, $c, $b)

However, I use the function in other files that I didn't want to change.

Matthew1980

7:34 pm on Jan 20, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there MikeTurpin,

Well setting the parameter to null does make php treat it as optional, and as this can be accessed a few ways, here is another example:-

function someFunction($a, $b, $c, $d = NULL)
{
$d = ((isset($d) && !empty($d)) ? $b : '');
...
}

Or something to that effect anyway (probably got my logic backwards though :))

Cheers,
MRb