How to I make a call to a function where I w开发者_开发问答ant to use some default args and some some I pass in:
function genericlist (array $arr, string $name, [string $attribs = null],
[string $key = 'value'], [string $text = 'text'],
[mixed $selected = NULL], [ $idtag = false], [ $translate = false])
I only want to pass in $arr, $name, $selected and use the default values for everything else, how do I do that? I know I could pass in the default values and go in order but I there must me another way. Thank you.
array_merge
might be able to give you a solution, if you're interested in using the arrays route:
function func1($args = array())
{
$defaults = array('X' => 10, 'Y' => 30);
$args = array_merge($defaults, $args);
// $args now has default arguments and user supplied arguments
return $args;
}
func1(); // array('X' => 10, 'Y' => 30)
func1(array('X' => 40)); // array('X' => 40, 'Y' => 30)
Well, either you do pass the default values indeed, either you reorder the arguments so as to put $selected before all other optional arguments.
Also, you can request for named parameters on PHP development forums.
I see two solutions:
- Create the function with null arguments. When a null value is supplied, check for it within the function and replace it with a default. This is round-about in that it's no longer specified in the prototype, but does offer the default value solution with minimal effort.
- Turn your prototype in to an array argument with key-value pairs. This is similar to the first solution, but you can use a method such as
array_merge
to combine the "default value" array and the newly passed argument values.
Example 1:
function abc($foo = null, $bar = null)
{
// defaulting parameters
if (is_null($foo)) $foo = 'Hello, world!'; // foo default value
if (is_null($bar)) $bar = 123.45; // bar default value
// on-ward with the function
}
// override bar, but not foo:
abc(null, 987.65);
Example 2:
function def($args)
{
// defaulting parameters
$args = array_merge(
array(
'foo' => 'Hello, world!', // Default foo value
'bar' => 123.45 // default bar value
),
$args // override with supplied values
);
// on-ward with the function
}
// override bar, but not foo
def(array('bar'=>987.65));
精彩评论