开发者

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 = arr开发者_如何学编程ay(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?


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.


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


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

Just make your function use the reference with &.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜