bothwell Posted December 13, 2008 Share Posted December 13, 2008 Say I've got the following function: function swap($fish,$human) { if ($human != '') { print "bicycle"; } else if ($fish != '') { print "aquarium"; } } Nice and simple. If I call this function with swap($fish,$human); then everything goes as expected, and I get the right output (an aquarium for a fish, and a bicycle for a human). But if I mix my variable order up, and go swap($human,$fish); instead, then I get the wrong output once I send my variable through the function (so instead the human gets the aquarium printout, and the fish gets a bicycle). What I don't understand is what's causing the swap? Why does the variable order in the function call have to match the variable order in the function declaration when the output for each variable is explicitly set inside the function? Thanks for any explanations Link to comment https://forums.phpfreaks.com/topic/136814-question-about-functions-and-order-of-variables/ Share on other sites More sharing options...
waynew Posted December 13, 2008 Share Posted December 13, 2008 function swap($fish,$human) { Because your function expects $fish to be the first parameter and $human to be the second parameter. You must always stick with the ordering of the parameters that your function takes in. Link to comment https://forums.phpfreaks.com/topic/136814-question-about-functions-and-order-of-variables/#findComment-714533 Share on other sites More sharing options...
Mark Baker Posted December 13, 2008 Share Posted December 13, 2008 Because the function doesn't know the variable names that were used to call it, only the values, so it uses the order of those values to assign those values to its own internal variables (as defined in your function definition). You might expect it to know that because you're calling the function with variables of the same name, they would be assigned to the functions local variable names of the same name, but this is impractical because I can call the function using variables of any name: $varA = 'sturgeon'; $varB = 'John'; swap($varA,$varB) or even no variables at all, but actual values: swap('Tuna','Janet') Link to comment https://forums.phpfreaks.com/topic/136814-question-about-functions-and-order-of-variables/#findComment-714711 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.