Passing Arguments by Reference


Here's something to know about functionswhen you pass an argument to a function in PHP, it's passed by value by default. That means that a copy of the data is passed to the function, not the actual data itself.

But what if you wanted to modify the original value that you pass to a function? For example, what if you wanted to add a little more to a text string that you pass to a function? In this example, we're trying to concatenate "No" and "worries." using a function named add_text:

 <?php     $string = "No ";     add_text($string);     echo $string;     function add_text($text)     {         $text .= "worries.";     } ?> 

If you run this script, you just see:

 No 

However, you can fix this script with a single character. You simply preface an argument that you pass to a function with &, and PHP will pass that argument by reference:

 $string = "No "; add_text($string); echo $string; function add_text(&$text) {     $text .= "worries."; } 

Now a reference to the original data ($string) is passed to the add_text function. That means you now have access to the original data in $string in the function. If you want to change that data, as we're doing here by appending "worries." to it, there's no problem. You can see what this looks like in a web page in phpbyref.php in Example 4-4.

Example 4-4. Passing data by reference, phpbyref.php
 <HTML>         <HEAD>             <TITLE>                 Passing data by reference             </TITLE>         </HEAD>         <BODY>             <H1>                 Passing data by reference             </H1>             <?php                 $string = "No ";                 add_text($string);                 echo $string;                 function add_text(&$text)                 {                     $text .= "worries.";                 }             ?>     </BODY> </HTML> 

And you can see the results in Figure 4-4, where we were able to successfully modify the original data in $string that was passed to the function. Cool.

Figure 4-4. Passing data by reference.


But be careful when you pass data by referenceyou can inadvertently alter the data in the original variable that was passed to you, thereby creating a bug that's very hard to track down (which is why passing by value is the default).



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net