Page 1 of 1

order of function arguments

Posted: Wed Jun 07, 2006 1:29 am
by Luke
I often run into the issue of having a function with like three arguments. Now the first argument is required, but the second and third have a default, but for some calls to this function, I will want to set both the first and second arguments (and rely on the default for the third) but then again in other cases, I need to set the first and third, and rely on the default for the second. I tried to explain that the best I could. I hope somebody understands my question.

FOR EXAMPLE:

Code: Select all

function do_something($foo, $arg2=true, $arg3=true){
    // Does something
}

// First call
do_something(10, false);

// Second call
do_something(10, whatever the default is, false);

Posted: Wed Jun 07, 2006 2:04 am
by Christopher

Code: Select all

function do_something($foo=null, $arg2=null, $arg3=null){
	$foo = $foo == null ? 'default for foo' : $foo;
	$arg2 = $arg2 == null ? 'default for arg2' : $arg2;
	$arg3 = $arg3 == null ? 'default for arg3' : $arg3;
	echo"$foo, $arg2, $arg3<br/>";
}

// First call
do_something(10, false);

// Second call
do_something(10, null, false);

Posted: Wed Jun 07, 2006 3:28 am
by Chris Corbyn
Yes. This is exactly what I do.

Don't make your "default" value part of the argument list. Make them NULL and then if they are identical to null (or false if it doesn't matter) then assign the defaults.

Posted: Wed Jun 07, 2006 6:04 pm
by nathanr
There are lots of weird and wonderful alternatives to this.. my favourite personally is just to create an array that holds all variables, any variables which need a default, simply declare before you do a thing, saves doing it repeatedly in functions. (and much easier to change)

Code: Select all

// Set the defaults
$some_array["value1"] = "hello world";
$some_array["value2"] = true;
$some_array["value3"] = 10;

//Grab some info
function grab_data($some_array) {
   $some_array["value1"] = $data_from_over_there;
   $some_array["value3"] = 6;
   return $some_array;
}

//Grab some more info
function grab_more_data($some_array) {
   $some_array["value1"] = $data_from_a_file;
   $some_array["value2"] = false;
   return $some_array;
}


function do_something($some_array){ 
    // Does something
    return $some_array;
} 

// First call 
print_r(do_something(grab_data($some_array))); 

// Second call 
print_r(do_something(grab_more_data($some_array)));
it works? 8O