Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using optional params 1

Status
Not open for further replies.

skiflyer

Programmer
Joined
Sep 24, 2002
Messages
2,213
Location
US
Is it possible to use named optional parameters?

Code:
function checkIt($one, $two=2, $three=3) {
  echo &quot;$one<BR>$two<BR>$three&quot;;
}

checkIt($one,$three=&quot;300&quot;);

Is basically what I want, I want to set the second optional parameter without having to fill in any value for the first.

Thanks,
Rob
 
Unfortunately, you can't do that in PHP. In order to be able to use the second parameter, the first must be present.

One workaround is to hand the function an associative array containing only the values you want to vary from the defaults. Then have the function assume default values for the array elements that aren't present.

Want the best answers? Ask the best questions: TANSTAAFL!
 
Good tip to keep in mind for future applications... overkill at the moment.

Do you happen to know if it's slated for 5.x?

-Rob
 
It's not that much extra programming to use the array. It only requires 5 or 6 lines of code, and those 5 or 6 lines can be abstracted to a separate function. I have an example at the end of this post.

Adding this feature in PHP 5? I doubt it. Most of the additional functionality in PHP 5.0 is going toward improving the OO aspects of the language.

Anyway, I can't think of more than a few languages that support that feature at all. And all of them require that you name the input parameters to do what you want to do. Which is basically creating an associative array on the fly.


Here's my code:
Code:
<?php

function set_defaults (&$inputs, $defaults)
{
	foreach ($defaults as $default_key => $default_value)
	{
		if (!array_key_exists ($default_key, $inputs))
		{
			$inputs[$default_key] = $default_value;
		}
	}
}

function myfunction ($foo)
{
	set_defaults ($foo, array ('one' => 2, 'two' => 1));
	
	print '<pre>';
	print_r ($foo);
	print '</pre>';
}

print '<html><body>';

myfunction (array('one' => 1, 'two' => 2));

myfunction (array('one' => 3));

myfunction (array());

print '</body></html>';	

?>

Want the best answers? Ask the best questions: TANSTAAFL!
 
There is a cheating way to do it, without using procedures or parameters, just have the piece of code that would be in the procedure in a file and include it where you would normally call the function, it will be able to use any variables within the scope of the bit it was called from, so just set the ones you need.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top