Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Return By Reference in PHP

Tags:

php

For some reason I have always assumed that most of the time a variable returned from a method would be returned by reference - after all on return; most methods would destroy the return value and it seems silly to make a copy, return it, then destroy the originals.

Does the above ever apply, or is it worth going through and making functions return by reference manually? I have a few methods that often pass large amounts of data between themselves and if it is the case it would be a cheap way of getting some more performance out of them.

Thanks for any comments!

like image 995
Meep3D Avatar asked Dec 30 '22 20:12

Meep3D


1 Answers

PHP does 'copy on write' anyway, so variables aren't actually copied until you actually modify the value. So you shouldn't need to worry about this.

Also from http://php.net/manual/en/language.references.return.php:

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.

like image 195
Tom Haigh Avatar answered Jan 08 '23 14:01

Tom Haigh