Concept

How does PHP pass arguments by reference?

ComputerScienceOne / Passing By Reference

"By default, all types (including numbers, strings, etc.) are passed by value. To be able to pass arguments by reference, we need to use slightly different syntax when defining our functions. To specify that a parameter is to be passed by reference, we place an ampersand, &, in front of it in the function signature. No other syntax is necessary. When you call the function, PHP automatically takes care of the referencing/dereferencing for you.\n\n<?php\n\nfunction swap($a, $b) {\n\n$t = $a;\n\n$a = $b;\n\n$b = $t;\n\n}\n\nfunction swapByRef(&$a, &$b) {\n\n$t = $a;\n\n$a = $b;\n\n$b = $t;\n\n}\n\n$x = 10;\n\n$y = 20;\n\nprintf(\"x = %d, y = %d\n\n\", $x, $y);\n\nswap($x, $y);\n\nprintf(\"x = %d, y = %d\n\n\", $x, $y);\n\nswapByRef($x, $y);\n\nprintf(\"x = %d, y = %d\n\n\", $x, $y);\n\n?>\n\nThe first function, swap(), passes both variables by value. Swapping the values only affects the copies of the parameters. The original variables $x and $y will be unaffected. In the second function, swapByRef(), both variables are passed by reference as there are ampersands in front of them. Swapping them inside the function swaps the original. Those familiar with pointers in C will note that this is the exact opposite of the C operator."

Related Ideas

How does PHP pass arguments by reference? | ComputerScienceOne | Bifalgorithm | Bifalgorithm