PHP:$var 和 &$var 有什么区别?

发布于 2024-10-09 14:09:30 字数 213 浏览 2 评论 0原文

有什么不一样

foreach ($my_array as $my_value) {
}

和: 和

foreach ($my_array as &$my_value) {
}

我可以请您举两个现实世界的例子来说明何时使用其中一种以及何时使用另一种吗?

What is the difference between

foreach ($my_array as $my_value) {
}

And:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

随遇而安 2024-10-16 14:09:30

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

一些原生 PHP 函数已经以这种方式工作,例如 shuffle()< /code>重新排列数组的内容。您会注意到这个函数不返回一个数组,您只需调用它即可:

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

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

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

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

请参阅 通过引用传递

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.

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.

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

See Passing by Reference.

地狱即天堂 2024-10-16 14:09:30

Jonathan 的回答很好地描述了这一点。为了完整起见,这里有两个示例:

  1. 仅读取值:

    $my_array = range(0,3);
    foreach ($my_array 作为 $my_value) {
        回显 $my_value 。 PHP_EOL;
    }
    
  2. 向每个元素添加一些数字(从而修改每个值):

    foreach ($my_array as &$my_value) {
        $我的值+= 42;
    }
    

    如果您不使用&$my_value,那么添加不会对$my_array产生任何影响。
    但是您可以不使用引用来编写相同的内容:

    foreach($my_array as $key=>$value) {
        $my_array[$key] = $value + 42;
    }
    

    不同之处在于,我们直接使用$my_array[$key]访问/更改原始值。

演示

Jonathan's answers describes it very well. Just for completeness, here are your two examples:

  1. Just reading values:

    $my_array = range(0,3);
    foreach ($my_array as $my_value) {
        echo $my_value . PHP_EOL;
    }
    
  2. Adding some number to each element (thus modifying each value):

    foreach ($my_array as &$my_value) {
        $my_value += 42;
    }
    

    If you don't use &$my_value, then the addition won't have any effect on $my_array.
    But you could write the same not using references:

    foreach($my_array as $key=>$value) {
        $my_array[$key] = $value + 42;
    }
    

    The difference is that we are accessing/changing the original value directly with $my_array[$key].

DEMO

棒棒糖 2024-10-16 14:09:30

当您在变量前加上 & 符号时,您就创建了一个“引用”。 PHP 引用就像计算机上的快捷方式或符号链接。您可以创建一个指针变量,它只是相同数据的另一个名称。

我没有看到使用这些有什么大的区别,除了你不复制保存内存的变量。当您传递变量时,您可以只传递引用和引用指向原始对象。

When you prefix a variable with an ampersand, you’re creating a “reference.” PHP references are like shortcuts or symlinks on your computer. You can create a pointer variable that is just another name for the same data.

I dont see a big difference in using these, except that you DONT COPY a variable saving memory. When you are passing variables you can just pass the reference and the reference points to the original object.

梓梦 2024-10-16 14:09:30

一个现实世界的例子 &当您需要用很少的代码行更改数组的内容时使用

foreach($arrFeed as &$objFeed)
  $objFeed['externalSrc'] = convertToLocalImage($objFeed['externalSrc']);

A real world example for & use is when you need to change the content of an array with very few lines of code

foreach($arrFeed as &$objFeed)
  $objFeed['externalSrc'] = convertToLocalImage($objFeed['externalSrc']);
苏佲洛 2024-10-16 14:09:30

我仅在必须读取 csv 文件才能知道分隔符是什么时才使用引用。只需取第一行:

$handle = fopen($file, "r");
$firstLine = fgets($handle);
fclose($handle);

然后使用此可能的分隔符

$delimiters = array(';' => 0,',' => 0,"\t" => 0,"|" => 0);

通过引用计数最常用的分隔符

foreach ($delimiters as $delimiter => &$count) {
    $count = count(str_getcsv($firstLine, $delimiter));
}
$delimiter =  array_search(max($delimiters), $delimiters);

I only use references when i have to read csv files to know what is the delimitier. Just take the first line:

$handle = fopen($file, "r");
$firstLine = fgets($handle);
fclose($handle);

Then with this possible delimitiers

$delimiters = array(';' => 0,',' => 0,"\t" => 0,"|" => 0);

Count by reference what is the most used

foreach ($delimiters as $delimiter => &$count) {
    $count = count(str_getcsv($firstLine, $delimiter));
}
$delimiter =  array_search(max($delimiters), $delimiters);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文