1

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.

1
  • what I do when I need something like this is to pass an associative array with the options. Commented Apr 29, 2014 at 14:47

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

The default values need to come after any non-default values as shown in example 5 on the function arguments page at PHP.net.

Comments

0

Try to examine variable function arguments in PHP.

2 Comments

@FranciscoCorrales, this is obviously a search query. You should be smart enough to copy it to the clipboard and paste into your favourite search engine. A learn answer is always better than a solve answer.
well, not that obvious to me, 'search' would do, 'examine' didn't give any clue. I love both learn answer, and solve answer, both the solution and the explanation... Thank you.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.