Solved: optional arguments

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
deltawing
Forum Commoner
Posts: 46
Joined: Tue Jun 14, 2005 2:55 pm

Solved: optional arguments

Post 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?
Last edited by deltawing on Thu Jun 16, 2005 9:53 am, edited 1 time in total.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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).
deltawing
Forum Commoner
Posts: 46
Joined: Tue Jun 14, 2005 2:55 pm

Post by deltawing »

Oh yeah, I've seen that default value thing before. I should've realised. Thanks.
Post Reply