NYCPHP Meetup

NYPHP.org

[nycphp-talk] Passing Arrays

Hans Zaunere hans at nyphp.org
Tue Oct 28 14:28:21 EST 2003



David Mintz wrote:

> On Tue, 28 Oct 2003, Analysis & Solutions wrote:
> 
> 
>>Hi Jim:
>>
>>On Mon, Oct 27, 2003 at 05:53:56PM -0500, Jim Smith wrote:
>>
>>>With PERL, if passing two arrays to a subroutine the arrays should be
>>>passed as references to ensure their integrity.

I'm not sure what 'integrity' means exactly in this case.

>>>Should this also be applied with PHP?

So I'm going to answer "no" here.  If integrity means "not copying the data the array contains" then you don't need to use the ampsersand (which is actually an alias, not a reference).  See caveat below.

>>Just curious, are you delcaring the function with arguments, or are you
>>grabbing them via func_get_args()?
>>
>>Either way, I don't believe you HAVE to.
>>
>>Are you changing data in either of those arrays inside the function?  If
>>so, then passing by reference is more efficient.
> 
> Is it not so that PHP -- I'm gonna try to say this intelligibly --
> doesn't actually copy data that is passed-by-value unless and until you
> change it inside the function? So pass-by-reference isn't necessary unless
> it's what you really mean. Stated differently, passing by reference just
> for the sake of saving memory doesn't save memory. True?

PHP uses "copy-on-write."  When you pass a variable into a function, the function gets a reference to the variable, and the contents are not copied.  They are, however, copied if you decide to write/change that variable in any way within the function.  If you want to avoid this "copying-on-write", ie. want to change the variable that is outside the scope of the function, you need to use an alias by specifying an ampersand in the function's prototype.

This *does not* apply to objects - they are copied all over the place, which is why PHP 5 will be a big improvement for those heavy OO developers out there.

H




More information about the talk mailing list