faqts : Computers : Programming : Languages : PHP : kms : Functions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 10 people (90%) answered Yes
Recently 7 of 8 people (88%) answered Yes

Entry

What is the difference between standard function arguments and passing by reference?
When should I pass function arguments by reference?

Jan 26th, 2000 22:27
Nathan Wallace, Richard Lynch


Passing by reference is good for two things:

1. Avoid passing a *HUGE* amount of data into a function which must copy
it all and then throw away that copy when it is done.  PHP3 does this
(and only this) using function (&$x)

2. Allow you to *alter* the actual value of a variable:

<?php
  function show($x){
    $x = 3;
    echo "In-Show: $x<BR>\n";
  }
  
  function munge(&$x){
    $x = 4;
    echo "In-Munge: $x<BR>\n";
  }
  
  $y = 2;
  echo "Pre-Show: $y<BR>\n";
  show($y);
  echo "Post-Show: $y<BR>\n";
  echo "Pre-Munge: $y<BR>\n";
  munge($y);
  echo "Post-Munge: $y<BR>\n";
?>

Assuming PHP4 behaves like C, this will output:

Pre-Show: 2
In-Show: 3
Post-Show: 2
Pre-Munge: 2
In-Munge: 4
Post-Munge: 4

NOTE THAT LAST LINE!!! munge actually *changed* the value of $y

Disclaimer:  I probably got the syntax wrong.  But the point should
still be valid...