Jump to content

Pointers and references: Difference between revisions

Line 562:
 
=={{header|PHP}}==
Actual Reference or Pointer "objects" don't exist in PHP, but you can simply tie any given variable or array value together with the "=&" operator. Adding the "&" symbol before a function name and the times a function is called causes the functions return values to be returned by reference. Adding the "&" synbol before any function parameter, and that parameter is passed by reference into the function.
 
As an additional note, the "global" keyword, simply references the variable from the $_GLOBALs superglobal array into a variable by the same name in the current scope. This is an important distinction as other functions that you call can actually re-reference the $_GLOBALS value to a different variable, and your function which used the "global" keyword is no longer actually linked to anything in the $_GLOBALS array.
 
<lang php><?php
Line 572 ⟶ 574:
$c = 7; //$c is not a reference; no change to $a or $b
unset($a); //won't unset $b, just $a.
 
/* Passing by Reference in and out of functions */
function &pass_out() {
global $filestr; //$exactly equivalent to: $filestr =& $_GLOBALS['filestr'];
 
$filestr = get_file_contents("./bigfile.txt");
return $_GLOBALS['filestr'];
}
function pass_in(&$in_filestr) {
echo "File Content Length: ". strlen($in_filestr);
 
/* Changing $in_filestr also changes the global $filestr and $tmp */
$in_filestr .= "EDIT";
echo "File Content Length is now longer: ". strlen($in_filestr);
}
 
$tmp = &pass_out(); // now $tmp and the global variable $filestr are linked
pass_in($tmp); // changes $tmp and prints the length
 
?></lang>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.