# functions returning references to function calls

- Thread: https://externals.io/message/3679
- Original archive: https://news-web.php.net/php.internals/3679
- Started by Brad Bulger on 2003-08-01T12:33:30+00:00
- Messages: 2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #3679 — Brad Bulger — 2003-08-01T12:33:30+00:00

URL: https://externals.io/message/3679#3679

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.

---

## #3691 — Zeev Suraski — 2003-08-01T21:48:12+00:00

URL: https://externals.io/message/3679#3691 · In reply to: #3679

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
