Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP arrays and pass-by-reference

Tags:

php

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?

like image 953
Bobby Jack Avatar asked May 26 '11 12:05

Bobby Jack


People also ask

Can you pass arrays by reference?

Arrays can be passed by reference OR by degrading to a pointer. For example, using char arr[1]; foo(char arr[]). , arr degrades to a pointer; while using char arr[1]; foo(char (&arr)[1]) , arr is passed as a reference. It's notable that the former form is often regarded as ill-formed since the dimension is lost.

Is PHP pass by reference or value?

It's by value according to the PHP Documentation. By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

Can we pass array as argument in PHP?

You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... } sendemail(array('a', 'b', 'c'), 10);

Is pass by reference faster PHP?

In fact, in most scenarios passing by value is faster and less memory intensive than passing by reference. The Zend Engine, PHP's core, uses a copy-on-write optimization mechanism that does not create a copy of a variable until it is modified.


2 Answers

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.

like image 124
Matthew Avatar answered Oct 17 '22 00:10

Matthew


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

like image 44
Lightness Races in Orbit Avatar answered Oct 17 '22 00:10

Lightness Races in Orbit