I’ve seen both before, and as far as I know, it’s pretty much subjective, but if given the option, which would you do and why? If the data were large, would there be any speed/memory benefit to one of them?
function processData(&$data_to_process) { // Pass by reference.
// do something to the data
}
// ... somewhere else
$this->processData($some_data);
or
function processData($data_to_process) { // Pass by value.
// do something to the data
return $data_to_process;
}
// ... somewhere else
$some_data = $this->processData($some_data);
PHP copies on write, so if the data doesn’t change in the function, using a reference only makes things run slower.
In your case, you are changing the data, so a copy will occur. Test with the following:
Run it once with
ref()and once withret(). My results:ref()
ret()
So, as you can see, PHP uses more memory when modifying the data in the function and returning it. So the optimal case is to pass by reference.
However, passing by reference can be dangerous if it’s not obvious that it is occurring. Often you can avoid this question altogether by encapsulating your data in classes that modify their own data.
Note that if you use objects, PHP5 always passes them by reference.