PHP:分配,传递和返回引用

时间:2016-07-28 14:10:23

标签: php reference

我已经阅读了这篇关于PHP中的引用的文章。

PHP References: How They Work, and When to Use Them

我知道它的语法,但我对在何时使用PHP中的引用感到有点困惑。你能给我一个真实世界的例子,我可以申请参考吗?是否有必要使用引用或我只能使用正常格式的函数?引用的真正目的是什么?

请你向我解释一下,我很容易理解。

1 个答案:

答案 0 :(得分:0)

使用引用的原因是您可以修改传递给函数的值。

这是一个例子

$nameOfUser = "Mr. Jones";

function changeName($name) { // Not passing the value by reference
    $name = "Foo";

    return $name;
}

changeName($nameOfUser);

/**
 * The echo below will output "Mr. Jones" since the changeName() function
 * doesn't really change the value of the variable we pass in, since we aren't
 * passing in a variable by reference. We are only passing in the value of the
 * $nameOfUser variable, which in this case is "Mr. Jones".
 */
echo $nameOfUser;

$nameOfUser = changeName($nameOfUser);

/**
 * This echo below will however output "Foo" since we assigned the returning
 * value of the changeName() function to the variable $nameOfUser
 */
echo $nameOfUser;

现在,如果我想在上面的第二个例子中使用引用获得相同的结果,我会这样做:

$nameOfUser = "Mr. Jones";

function changeName(&$name) { // Passing the value by reference
    $name = "Foo";

    return $name;
}

changeName($nameOfUser);

/**
 * The echo below will output "Foo" since the changeName() function
 * changed the value of the variable we passed in by reference
 */
echo $nameOfUser;

我希望我的例子是可以理解的,并且我已经让你更好地了解了引用的工作原理。

我没有一个例子,说明何时需要参考资料,因为我个人认为最好返回价值并按照这种方式设置。修改传入函数的变量可能会混淆使用该函数的用户。