Variable, value and reference in PHP?

  • Thread starter Thread starter Tony Y
  • Start date Start date
T

Tony Y

Guest
code one:
$white = "snow";
$black = $white;

code two:
$white = "snow";
$black = & $white;

Whether the "code one" is equal to "code two"? both value of $white is not copied
 
On code one you will have the $black copying any value that the variable $white have. If $white changes it's value later, $black would remain with the same value.

For example:

code 1:
$white = "white";
$black = $white;
echo "\$white = {$white} and \$black = {$black}";
// the result will be $white = white and $black = white
// now changing the value of $white to gray
$white = "gray";
echo "\$white = {$white} and \$black = {$black}";
// the result will be $white = gray and $black = white

Now on code 2 you have the variable by reference, so if the variable changes it's value later, it would affect the variable that receives it as well.

For example:
$white = "white";
$black = &$white;
echo "\$white = {$white} and \$black = {$black}";
// the result will be $white = white and $black = white
// now changing $white value to gray
$white = "gray";
echo "\$white = {$white} and \$black = {$black}";
// the result will be $white = gray and $black = gray

Have fun
 
Back
Top