PHP 中的引用賦值運算子
    
    
            Kevin Amayi
    2023年1月30日
    
    PHP
    PHP Operator
    
- 
          
            在 PHP 中使用 =&運算子建立一個不存在的變數
- 
          
            在 PHP 中使用 =&運算子將多個變數指向相同的值(記憶體位置)
- 
          
            在 PHP 中使用 =&運算子連結多個變數
- 
          
            在 PHP 中使用 =&運算子取消多個變數的連結
 
本文演示了建立一個不存在的變數、將多個變數指向同一個值、連結多個變數以及使用引用賦值或 =& 運算子或在 PHP 中取消連結多個變數。
在 PHP 中使用 =& 運算子建立一個不存在的變數
    
我們將建立一個陣列並使用按引用賦值運算子來建立一個陣列變數,而無需最初宣告該變數。
<?php
    $test = array();
    $test1 =& $test['z'];
    var_dump($test);
?>
輸出:
array(1) {
	["z"]=>
	&NULL
}
在 PHP 中使用 =& 運算子將多個變數指向相同的值(記憶體位置)
我們將建立一個變數,為其賦值,然後使用引用賦值運算子使其他變數指向與第一個變數相同的記憶體位置。
<?php
    $firstValue=100;
    $secondValue =& $firstValue;
    echo "First Value=".$firstValue."<br>";
    echo "Second Value=". $secondValue."<br>";
    $firstValue = 45000;
    echo "After changing the value of firstValue, secondValue will reflect the firstValue  because of =&","<br>";
    echo "First Value=". $firstValue."<br>";
    echo "Second Value=". $secondValue;
?>
輸出:
First Value=100
Second Value=100
After changing the value of firstValue, secondValue will reflect the firstValue  because of =&
First Value=45000
Second Value=45000
在 PHP 中使用 =& 運算子連結多個變數
我們將建立一個變數,為其賦值,然後使用引用賦值運算子將其他變數連結到初始變數。它們都指向初始變數值。
<?php
    $second = 50;
    $first =& $second;
    $third =& $second;
    $fourth =& $first;
    $fifth =& $third;
    // $first, $second, $third, $fourth, and $fifth now all point to the same data, interchangeably
    //should print 50
    echo $fifth;
?>
輸出:
50
在 PHP 中使用 =& 運算子取消多個變數的連結
我們將建立兩個變數併為它們賦值。然後使用引用運算子來連結和取消連結其他變數。
變數指向不同的值。
<?php
    $second = 50;
    $sixth = 70;
    $first =& $second;
    $third =& $second;
    $fourth =& $first;
    $fifth =& $third;
    // $first, $second, $third, $fourth, and $fifth now all point to the same data, interchangeably
    //unlink $fourth from our link, now $fourth is linked to $sixth and not $third
    $fourth = $sixth;
    echo $fourth;
?>
輸出:
70
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe