954,597 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Function argument default to another argument

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
Newbie Poster
2 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

What is the use case for something like this?
It seems trivial to implement something like this within the function.

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


and if $d has to always be supplied you could just pass the value of $b to the function a second time.

function someFunction($a, $b, $c, $d)
{
  ...
}
//usage
$a = 2;
$b = 4;
$c = 5;
$value = someFunction($a, $b, $c, $b);
mschroeder
Work Harder
Team Colleague
666 posts since Jul 2008
Reputation Points: 279
Solved Threads: 131
 

Didn't think of using null and is_null, but that's much better. Thanks very much.

miketurpin
Newbie Poster
2 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: