【发布时间】:2016-07-29 10:57:59
【问题描述】:
我已经阅读了这篇关于 PHP 引用的文章。
PHP References: How They Work, and When to Use Them
我知道它的语法,但对于何时在 PHP 中使用引用有点困惑。你能给我一个我可以应用参考的真实世界的例子吗?是否有必要使用引用或者我可以使用正常格式的函数?引用的真正目的是什么?
请你解释一下,我很容易理解。
【问题讨论】:
我已经阅读了这篇关于 PHP 引用的文章。
PHP References: How They Work, and When to Use Them
我知道它的语法,但对于何时在 PHP 中使用引用有点困惑。你能给我一个我可以应用参考的真实世界的例子吗?是否有必要使用引用或者我可以使用正常格式的函数?引用的真正目的是什么?
请你解释一下,我很容易理解。
【问题讨论】:
使用引用的原因是为了修改传递给函数的值。
这是一个例子
$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;
我希望我的示例是可以理解的,并且希望我能让您更好地了解引用的工作原理。
我没有示例说明何时需要引用,因为我个人认为返回值并以这种方式设置会更好。修改传入函数的变量可能会使使用该函数的用户感到困惑。
【讨论】: