PHP:变量名前面的 & 是什么意思?

问题描述 投票:0回答:4

变量名前面的

&
是什么意思?

例如

&$salary
$salary

php
4个回答
88
投票

它传递对变量的引用,因此当编辑分配了该引用的任何变量时,原始变量都会更改。它们在创建更新现有变量的函数时非常有用。您可以简单地传递对函数的引用,而不是硬编码更新哪个变量。

示例

<?php
    $number = 3;
    $pointer = &$number;  // Sets $pointer to a reference to $number
    echo $number."<br/>"; // Outputs  '3' and a line break
    $pointer = 24;        // Sets $number to 24
    echo $number;         // Outputs '24'
?>

3
投票

它是一个参考,就像其他语言(例如 C++)一样。 文档中有一个关于它的部分。


3
投票

在 PHP 世界中,引用就像一面神奇的镜子,反映代码中的更改。让我们用一些异想天开的例子来揭开它们的神秘面纱:

从官方文档了解更多信息

1.英雄与恶棍的故事

$hero = 'Harry';              // Our brave hero's name
$darkLord = &$hero;           // The villain takes on the hero's guise
$darkLord = "Behold, I am $darkLord, the Dark Lord";  // Embracing darkness

echo $darkLord;   // "Behold, I am Harry, the Dark Lord"
echo $hero;       // Also echoes: "Behold, I am Harry, the Dark Lord"

在这里,$darkLord 和 $hero 具有相同的身份,揭示了我们角色的双重性。

2.禁忌咒语:引用限制

$age = 25;
$referenceToAge = &$age;      // Perfectly acceptable

$referenceToCalculation = &(24 * 7);  // Forbidden incantation; referencing an unnamed expression

function getAge() {
   return 25;
}

$referenceToFunction = &getAge();    // Spells backfire; can't directly reference a function return

3.传递引用之谜

function changeName(&$person) {
  $person = 'Voldemort';
}

$name = 'Harry';

changeName($name); // Alas! The hero falls to the dark side

echo $name; // "Voldemort" rises, echoing across the realm

但是要小心!传递变量引用以外的任何内容都会引发混乱。

4.追求精度:仅限命名变量

$powerLevel = 9000;                      // Our hero's power level
$referenceToPowerLevel = &$powerLevel;   // Power harnessing at its finest

$referenceToExpression = &(10 * 5);      // Quest halted; can't reference an unnamed expression

function getPowerLevel() {
   return 9000;
}

$referenceToFunction = &getPowerLevel(); // Journey thwarted; can't directly reference a function return

5.共享秘密的传奇:数组和引用

$teamA = ['Gandalf', 'Frodo', 'Aragorn'];    // Fellowship of the Ring
$teamB = &$teamA;                             // Allies bound by fate

array_push($teamB, 'Legolas');                // A new member joins the fellowship

print_r($teamA);   // The roster echoes across Middle-earth
print_r($teamB);   // Both teams share the same quest

在阵列领域,参考文献建立了牢不可破的纽带,在他们的追求中团结盟友。

6.传奇永存:持久参考

function &createEternalFlame() {
    static $flame;                      // Eternal flame, ever-burning
    
    if (!$flame) {
        $flame = 'Eternal Flame';       // Igniting the essence of eternity
    }
    
    return $flame;                      // A beacon of hope for all who seek it
}

$torch = &createEternalFlame();         // Harnessing the essence of eternity

echo $torch;    // "Eternal Flame" illuminates the darkness

通过静态引用,传奇诞生,并随着时间的推移使其本质永垂不朽。

------------ 了解更多 ------------


-1
投票

它用于通过引用传递变量。

阅读 PHP 文档中的更多内容

© www.soinside.com 2019 - 2024. All rights reserved.