PHP remove “reference” from a variable.

后端 未结 4 2072
旧巷少年郎
旧巷少年郎 2021-01-11 14:18

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

相关标签:
4条回答
  • 2021-01-11 14:36

    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";
    
    0 讨论(0)
  • 2021-01-11 14:42
    $a = 1;
    $b = &$a;
    
    unset($b);
    // later
    $b = null;
    
    0 讨论(0)
  • 2021-01-11 14:45

    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
    
    0 讨论(0)
  • 2021-01-11 14:48

    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.
    
    0 讨论(0)
提交回复
热议问题