Reputation: 8586
I'd like to make my life easier avoiding to pass some preset variables to a function in PHP.
For example, this works:
function test1($var2,$var3,$var1=1){
return '$var1='.$var1.'+$var2='.$var2.'+$var3'.$var3;
}
echo test1($var2=2,$var3=3);
#$var1=1+$var2=2+$var33
But this doesn't (without the warnings):
function test($var1=1,$var2,$var3){
return '$var1='.$var1.'+$var2='.$var2.'+$var3'.$var3;
}
echo test($var2=2,$var3=3);
#Warning: Missing argument 3 for test(), called in /var/www/atpc.info/f/f/m/t.php on line 6 and defined in /var/www/atpc.info/f/f/m/t.php on line 3
#Notice: Undefined variable: var3 in /var/www/atpc.info/f/f/m/t.php on line 4
#$var1=2+$var2=3+$var3
Maybe the only way to make this to happen is always to put to the end of the line the preset variables. Is it?
Thanks for any light.
Upvotes: 1
Views: 186
Reputation: 9768
You might make your life easier, but it might result in sloppy code where at some points you SHOULD be passing a parameter and you forget but the code didn't throw any errors. That's my take.
Upvotes: 0
Reputation: 5719
The default values need to come after any non-default values as shown in example 5 on the function arguments page at PHP.net.
Upvotes: 1
Reputation: 146340
Oy... that is not how you pass variables in PHP....
To send variables:
function test($var1=1,$var2=1,$var3=1){ //default 1, 1, 1
return '$var1='.$var1.'+$var2='.$var2.'+$var3'.$var3;
}
echo test(2,3); //only sent for var1 and 2
echo test(null, 2, 3); //only sent for var2 and 3
echo test(); //default for all
Upvotes: 2