变量名前面的
&
是什么意思?
例如
&$salary
与 $salary
它传递对变量的引用,因此当编辑分配了该引用的任何变量时,原始变量都会更改。它们在创建更新现有变量的函数时非常有用。您可以简单地传递对函数的引用,而不是硬编码更新哪个变量。
示例
<?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'
?>
它是一个参考,就像其他语言(例如 C++)一样。 文档中有一个关于它的部分。
在 PHP 世界中,引用就像一面神奇的镜子,反映代码中的更改。让我们用一些异想天开的例子来揭开它们的神秘面纱:
$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 具有相同的身份,揭示了我们角色的双重性。
$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
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
但是要小心!传递变量引用以外的任何内容都会引发混乱。
$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
$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
在阵列领域,参考文献建立了牢不可破的纽带,在他们的追求中团结盟友。
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
通过静态引用,传奇诞生,并随着时间的推移使其本质永垂不朽。
它用于通过引用传递变量。