I have the code below. I want to change $b to use it again with values. If I do so it changes $a as well. How can I assign a value to $b again after previously assigning it
First of all: Creating a reference from $a
to $b
creates a connection (for the lack of a better word) between the two variables, so $a
changing when $b
changes is exactly the way it is meant to work.
So, assuming you want to break the reference, the easiest way ist
unset($b);
$b="new value";
$a = 1;
$b = &$a;
unset($b);
// later
$b = null;
The answer by @xdazz is correct, but just to add the following great example from the PHP Manual which gives an insight into what PHP is doing under the hood.
In this example you can see that $bar
within the function foo() is a static reference to a function scope variable.
Unsetting $bar
removes the reference but doesn't deallocate the memory:
<?php
function foo()
{
static $bar;
$bar++;
echo "Before unset: $bar, ";
unset($bar);
$bar = 23;
echo "after unset: $bar\n";
}
foo();
foo();
foo();
?>
The above example will output:
Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23
See explanation inline
$a = 1; // Initialize it
$b = &$a; // Now $b and $a becomes same variable with just 2 different names
unset($b); // $b name is gone, vanished from the context But $a is still available
$b = 2; // Now $b is just like a new variable with a new value. Starting new life.