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 can PHP pass variables by reference to return multiple quadratic roots?ComputerScienceOne · Quadratic Roots
- How can pointers be used to pass variables by reference?ComputerScienceOne · Passing By Reference
- How do pointers pass values by reference in C?ComputerScienceOne · Function Pointers
- How do you invoke functions that accept pointer parameters?ComputerScienceOne · Passing By Reference
- What are the key features of functions in PHP?ComputerScienceOne · Declaring Functions
- How can functions be assigned to variables and invoked as callbacks?ComputerScienceOne · Function Pointers
- How can pass-by-reference parameters return both roots of a quadratic equation?ComputerScienceOne · Quadratic Roots
- How can you check for a NULL pointer and dereference a valid pointer?ComputerScienceOne · Passing By Reference