Page 1 of 1

Custom function, set default argument values to variables

Posted: Wed Dec 10, 2008 5:51 am
by batfastad
Hi everyone
I'm used to creating my own functions, and functions with optional arguments.

But when I try something like this:

Code: Select all

function my_function($arg1=$var1, $arg2=$var2, $arg3=$var3) {
    //do stuff
}
I get a Parse error: syntax error, unexpected T_VARIABLE

I guess it's not possible to set the default of an optional argument to a variable value. Is there a way to do what I'm looking for?
Or do I have to explicitly tell the function what the default value is?

Cheers, B

Re: Custom function, set default argument values to variables

Posted: Wed Dec 10, 2008 7:40 am
by Mark Baker
batfastad wrote:I guess it's not possible to set the default of an optional argument to a variable value. Is there a way to do what I'm looking for?
Or do I have to explicitly tell the function what the default value is?
Correct, you can't set a default value to a variable because the script is compiled (including setting function defaults) before it is executed, and the variable is set during execution.

You can, however, set defaults to constants

Code: Select all

 
define ('const1','thisValue');
define ('const2','thatValue');
define ('const3','theOtherValue');
 
function my_function($arg1=const1, $arg2=const2, $arg3=const3) {
    //do stuff
}
 
An ugly alternative:

Code: Select all

 
function my_function($arg1=null, $arg2=null, $arg3=null) {
    global $var1, $var2, $var3;
    if (is_null($arg1)) { $arg1 = $var1; }
    if (is_null($arg2)) { $arg2 = $var2; }
    if (is_null($arg3)) { $arg3 = $var3; }
    //do stuff
}
 

Re: Custom function, set default argument values to variables

Posted: Wed Dec 10, 2008 9:49 am
by batfastad
Constants!! Cool :D
I've been doing PHP for a couple of years now and didn't realise you could user-define constants.
Probably useful for things like DB details and passwords etc.

Although from a bit of reading up, constants are slightly slower so probably best not to use on a wide scale

Thanks for all the info :lol: