Page 1 of 1

Solved: optional arguments

Posted: Thu Jun 16, 2005 7:19 am
by deltawing
I want to make some arguments of my function optional. Take this example, based on how I would do this in other scripting languages:

Code: Select all

function blah($doowop)
{
	if (!$doowop)
	{
		return 'false';
	}
	
	else
	{
		return $doowop;
	}
}

print blah();
(noting that $doowop never takes a zero value

I have also tried "if($doowop == null)".

Both options work, but return the warning "Missing argument 1 for blah() in c:\program files\easyphp1-7\www\u2wiki\test.php on line 1"

What's the cleanest way of doing this, without lots of messy error handling?

Posted: Thu Jun 16, 2005 7:26 am
by CoderGoblin

Code: Select all

function my_funct($myvar="") {
  if (empty($myvar)) {
    //Doesn't exist
  } else {
    //It exists
  }
}
Of course you default it to the type expected, 0 if integer etc. If the parameter can be passed in as "" or 0 etc. you may want to look at func_num_args.

It should also be noticed that the order of placement is important (defaults only after required).

Posted: Thu Jun 16, 2005 9:40 am
by deltawing
Oh yeah, I've seen that default value thing before. I should've realised. Thanks.