Jump to content

&$variable


raku

Recommended Posts

From the manual:

 

PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa. 

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable).

 

If it doesnt make things clear, go to this page and take a look at the examples.

Link to comment
https://forums.phpfreaks.com/topic/101901-variable/#findComment-521527
Share on other sites

Without the "&" the value of $x is passed to the function

<?php  
$x = 0;

function foo ($var)                              // pass by value
{
    $var += 1;
    return $var;
}

echo $x, '<br>';
echo foo ($x), '<br>'; 
echo $x, '<br>';

?>

 

With the "&", variable $x is passed by reference, so the variable inside the function is the same one as that outside

<?php  
$x = 0;

function bar (&$var)                               // pass by reference
{
    $var += 1;
    return $var;
}

echo $x, '<br>';
echo bar ($x), '<br>'; 
echo $x, '<br>';                                   // $x is incremented

?>

Link to comment
https://forums.phpfreaks.com/topic/101901-variable/#findComment-521533
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.