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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小柴没吃饱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值