什么时候可以在PHP中使用按引用传递? [英] When is it good to use pass by reference in PHP?

查看:153
本文介绍了什么时候可以在PHP中使用按引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,如果将大数组传递给函数,则需要通过引用传递它,这样才不会将其复制到浪费内存的新函数中.如果您不希望修改它,则可以通过const引用传递它.

In C++ if you pass a large array to a function, you need to pass it by reference, so that it is not copied to the new function wasting memory. If you don't want it modified you pass it by const reference.

任何人都可以验证通过引用传递也可以在PHP中节省我的内存.我知道PHP不会将地址用于C ++之类的引用,这就是为什么我有点不确定的原因.这就是问题.

Can anyone verify that passing by reference will save me memory in PHP as well. I know PHP does not use addresses for references like C++ that is why I'm slightly uncertain. That is the question.

推荐答案

以下内容不适用于对象,因为此处已对此进行了说明.仅当您计划修改传递的值时,通过引用传递数组和标量值才可以节省您的内存,因为PHP使用更改时复制(即写时复制)策略.例如:

The following does not apply to objects, as it has been already stated here. Passing arrays and scalar values by reference will only save you memory if you plan on modifying the passed value, because PHP uses a copy-on-change (aka copy-on-write) policy. For example:

# $array will not be copied, because it is not modified.
function foo($array) {
    echo $array[0];
}

# $array will be copied, because it is modified.
function bar($array) {
    $array[0] += 1;
    echo $array[0] + $array[1];
}

# This is how bar shoudl've been implemented in the first place.
function baz($array) {
    $temp = $array[0] + 1;
    echo $temp + $array[1];
}


# This would also work (passing the array by reference), but has a serious 
#side-effect which you may not want, but $array is not copied here.
function foobar(&$array) {
    $array[0] += 1;
    echo $array[0] + $array[1];
}

总结:

  • 如果您正在处理非常大的数组并计划在函数内部对其进行修改,则实际上应该使用引用来防止其被复制,否则可能会严重降低性能甚至耗尽内存限制.

  • If you are working on a very large array and plan on modifying it inside a function, you actually should use a reference to prevent it from getting copied, which can seriously decrease performance or even exhaust your memory limit.

但是,如果可以避免的话(小数组或标量值),我将始终使用功能样式的方法,而不会产生副作用,因为一旦您通过引用传递了某些内容,就永远不可能确保在函数调用之后可以保留传递的变量,这有时会导致令人讨厌且难以发现的错误.

If it is avoidable though (that is small arrays or scalar values), I'd always use functional-style approach with no side-effects, because as soon as you pass something by reference, you can never be sure what passed variable may hold after the function call, which sometimes can lead to nasty and hard-to-find bugs.

绝不能通过引用传递IMHO标量值,因为对性能的影响不能大到足以证明代码失去透明性.

这篇关于什么时候可以在PHP中使用按引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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