Bifalgorithm post · Computer science one · Passing By Reference

How does PHP pass arguments by reference?

How does PHP pass arguments by reference? (Computer science one · Passing By Reference) — "By default, all types (including numbers, strings, etc.) are passed…

Ideas in this flowchart

  • PHP argument passing: by value versus by reference
  • By default, all types, including numbers and strings, are passed by value.
  • Passing arguments by reference requires different function-definition syntax.
  • Place an ampersand (&) before each referenced parameter; no other syntax is necessary.
  • When the function is called, PHP automatically manages referencing and dereferencing.
  • The code example compares swap() with swapByRef() using $x = 10 and $y = 20.
  • swap() passes copies by value, so swapping affects only the parameter copies and leaves $x and $y unchanged.
  • swapByRef() passes both parameters by reference, so swapping inside the function changes the original variables.
  • The reference syntax differs from the operator used for pointers in C.
Feed/

How does PHP pass arguments by reference?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.