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
相关文章
|
2月前
|
PHP
PHP运算符
PHP运算符
18 0
|
10月前
|
PHP
PHP实现自制随机图片API- 调用文件夹和引用网络图片
PHP实现随机图片API- 调用文件夹和引用网络图片
112 0
|
5月前
|
PHP
今天遇到有趣的php引用题目
今天遇到有趣的php引用题目
18 0
|
5月前
|
PHP Python
关于python变量的再次折腾,没有PHP的引用赋值
今天,重看php文档的时候,发现了这样的讲法
15 0
|
6月前
|
数据库连接 PHP 数据库
PHP的引用操作符& 的使用及注意事项
PHP的引用操作符& 的使用及注意事项
|
8月前
|
PHP
PHP 比较运算符
PHP 比较运算符
23 0
|
8月前
|
PHP
PHP 连接运算符
PHP 连接运算符
25 0
|
11月前
|
PHP
PHP——运算符
PHP——运算符