Jump to content

passing variables, arays, objects by reference


Liquid Fire

Recommended Posts

I have been told that i should never pass by refernce in C++ becuase is it slower.  The zend engine will automaticaly pass by refernce and if i change the pass variable the engine will then make a copy of the variable so it will only change the variable inside that function and not the pass variabel too(as if it were pass by reference.  Is this true?

 

Also when declaring a new class should i do:

 

file_object = new CFile();

 

or

 

file_object =& new CFile();

 

Yes, PHP uses "copy on write" for function arguments.  If you pass a huge array into a function, it will not be copied unless you modify it, in which case a copy is triggered at the point of modification.

 

Similarly with foreach loops over an array - if you modify the original array within a foreach loop, then a copy is triggered, and all modifications are made on the copy.  At the end of the foreach loop, the original array is replaced with the modified version.  This allows a foreach loop to run consistently even if the array is modified during the loop.

 

The only thing I use references for in PHP is when I want to pass a large data structure to a function which will modify that data structure, such as a function that will fill in extra data in a large array.

 

I can't help with the class stuff, sorry.. but I'm pretty sure that PHP5 does NOT need references when creating objects.  PHP4, maybe.  If you don't get a reply, try asking in the OO sub-forum.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.