Php:$var 和 &$var 有什么区别? [英] Php: what's the difference between $var and &$var?

查看:26
本文介绍了Php:$var 和 &$var 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别

foreach ($my_array as $my_value) {
}

还有:

foreach ($my_array as &$my_value) {
}

?

我能否请您举两个真实世界的例子,说明何时使用一个,何时使用另一个?

May I ask you to give me two real-world examples of when to use one and when you use the other?

推荐答案

第一个示例创建值的副本,而第二个示例使用对原始值的引用.所以在第一个 foreach 运行后,原始数组仍然没有改变.在第二个 foreach 之后,原始数组可能已被修改,因为它是通过引用处理的.

The first example creates a copy of the value, whereas the second uses a reference to the original value. So after the first foreach runs, the original array is still untouched. After the second foreach the original array could have been modified since it was handled by reference.

一些原生 PHP 函数已经以这种方式工作,例如 shuffle() 重新排列数组的内容.你会注意到这个函数不返回一个数组,你只是调用它:

Some native PHP functions already work this way, such as shuffle() which rearranges the contents of your array. You'll notice that this function doesn't return an array, you just call it:

$myArray = array('foo', 'bar', 'fizz', 'buzz');
shuffle( $myArray );
// $myArray is now shuffled

它发挥了它的魔力,因为它通过引用来处理数组,而不是创建它的副本.

And it works its magic since it works with the array by reference rather than creating a copy of it.

然后有些函数不通过引用传递任何东西,而是处理原始值的副本,例如 ucwords() 返回新的结果字符串:

Then there are functions that don't pass anything by reference but rather deal with a copy of the original value, such as ucwords() which returns the new resulting string:

$myString = "hello world";
$myString = ucwords( $myString );
// $myString is now capitalized

参见通过引用传递.

这篇关于Php:$var 和 &$var 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆