4

我已经编写并使用了很多 PHP 函数和变量,其中原作者编写了原始代码,我不得不继续开发产品,即。Joomla 组件/模块/插件,我总是想出这个问题:

附加到函数或变量的“&”符号如何影响结果?

例如:

$variable1 =& $variable2;

或者

function &usethisfunction() {
}

或者

function usethisfunction(&thisvariable) {
{

我尝试搜索 PHP 手册和其他相关资源,但找不到任何专门解决我的问题的内容。

4

3 回答 3

7

这些被称为引用

下面是一些“常规”PHP 代码的示例:

function alterMe($var) {
    $var = 'hello';
}

$test = 'hi';
alterMe($test);
print $test; // prints hi

$a = 'hi';
$b = $a;
$a = 'hello';
print $b; // prints hi

这就是您可以使用引用实现的目标:

function alterMe(&$var) {
    $var = 'hello';
}

$test = 'hi';
alterMe($test);
print $test; // prints hello

$a = 'hi';
$b &= $a;
$a = 'hello';
print $b; // prints hello

详细的细节在文档中。然而,本质上:

PHP 中的引用是一种通过不同名称访问相同变量内容的方法。它们不像 C 指针;相反,它们是符号表别名。注意在PHP中,变量名和变量内容是不同的,所以同样的内容可以有不同的名字。最接近的类比是 Unix 文件名和文件 - 变量名是目录条目,而变量内容是文件本身。引用可以比作​​ Unix 文件系统中的硬链接。

于 2009-06-16T02:26:15.297 回答
2
<?php

$a = "hello";   # $a points to a slot in memory that stores "hello"
$b = $a;        # $b holds what $a holds

$a = "world";
echo $b;        # prints "hello"

现在如果我们添加 &

$a = "hello";   # $a points to a slot in memory that stores "hello"
$b = &$a;   # $b points to the same address in memory as $a

$a = "world";

# prints "world" because it points to the same address in memory as $a.
# Basically it's 2 different variables pointing to the same address in memory
echo $b;        
?>
于 2009-06-16T02:41:19.363 回答
1

这是一个参考。它允许 2 个变量名指向相同的内容。

于 2009-06-16T02:29:15.913 回答