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