Bobby Jack
Bobby Jack

Reputation: 16018

PHP arrays and pass-by-reference

The following pattern used to be possible in PHP:

function foo($arr)
{
    // modify $arr in some way
    return $arr;
}

This could then be called using pass-by-value:

$arr = array(1, 2, 3);
$newarr = foo($arr);

or pass-by-reference:

$arr = array(1, 2, 3);
foo(&$arr);

but "Call-time pass-by-reference has been deprecated". Modifying the function signature:

function foo(&$arr)

will handle the pass-by-reference case, but will break the dual-purpose nature of the original function, since pass-by-value is no longer possible.

Is there any way around this?

Upvotes: 10

Views: 8031

Answers (4)

Matthew
Matthew

Reputation: 48284

I think this is as close as you get:

function foo(&$bar) { ... }

foo($array);                // call by reference
$bar = foo($_tmp = $array); // call by value

Unfortunately it will require some changes to every call.

Upvotes: 5

mario
mario

Reputation: 145482

A simple workaround is to prepare a wrapper function:

function foo($arr) {
    return foo_ref($arr);
}

function foo_ref(&$arr) {
    ...

Then depending on the current use, either invoke the normal foo() or the foo_ref() if you want the array to be modified in place.


There is also a common array(&$wrap) parameter cheat, but that doesn't seem suitable in your case. A more contemporary workaround would be this tricky trick:

// pass by value
foo($array);

// pass by reference (implicitly due to being an object)
foo($array = new ArrayObject($array));

This allows for similar reference passing to unprepared functions. Personally I would prefer keeping the E_DEPRECATED warning and the intended syntax for this purpose.

Upvotes: 1

alex
alex

Reputation: 490143

Sadly, I don't believe there is a way around it.

Just make your function use the reference with &.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

The dual-purpose nature was stupid, which is why the behaviour is deprecated. Modify the function signature, as you suggest.

Upvotes: 2

Related Questions