Custom function, set default argument values to variables

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
User avatar
batfastad
Forum Contributor
Posts: 433
Joined: Tue Mar 30, 2004 4:24 am
Location: London, UK

Custom function, set default argument values to variables

Post 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
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Custom function, set default argument values to variables

Post 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
}
 
User avatar
batfastad
Forum Contributor
Posts: 433
Joined: Tue Mar 30, 2004 4:24 am
Location: London, UK

Re: Custom function, set default argument values to variables

Post 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:
Post Reply