diolemo
diolemo

Reputation: 2671

PHP remove "reference" from a variable.

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 as a reference to $a?

$a = 1;
$b = &$a;

// later
$b = null;

Upvotes: 18

Views: 6922

Answers (4)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57680

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 a new life.

Upvotes: 18

Paul Bain
Paul Bain

Reputation: 4397

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

Upvotes: 5

Eugen Rieck
Eugen Rieck

Reputation: 65314

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";

Upvotes: 3

xdazz
xdazz

Reputation: 160923

$a = 1;
$b = &$a;

unset($b);
// later
$b = null;

Upvotes: 8

Related Questions