functions returning references to function calls

php.internals

Brad Bulger

23 years ago
Hello. I found in PEAR DB class something that seemed like small BC issue. The package maintainer thought it sounded like bug. If anyone would comment? function &foo() { return new barclass; } gives error saying PHP Fatal error: Only variables or references can be returned by reference this is correct for php 5, yes? same as function &foo() { $a = array(1); return array_keys($a); } which gives same error in 5, but is acceptable in 4. Thank you.

Zeev Suraski

23 years ago
At 15:33 01/08/2003, Brad Bulger wrote:
>Hello. I found in PEAR DB class something that seemed like small BC issue. >The package maintainer thought it sounded like bug. If anyone would comment? > >function &foo() { return new barclass; } > >gives error saying >PHP Fatal error: Only variables or references can be returned by reference > >this is correct for php 5, yes? same as > >function &foo() { $a = array(1); return array_keys($a); } > >which gives same error in 5, but is acceptable in 4. > >Thank you.
It's problematic in both versions, in PHP 4 it's going to create memory corruption (which may or may not lead to visible symptoms), and in PHP 5 it's currently caught and avoided. We plan on trying to fix it so that it works in PHP 5. If you want to write code that will work across versions, my recommendation is that you use a temporary variable for now, e.g.: function &foo() { $rv =& new barclass; return $rv; } Ugly, but works. Zeev