Return a PHP array by reference

Thursday, July 28. 2011

Return a PHP array by reference

Looks like I'm using way to much Java in these days... I'm starting to forget PHP knowledge. Today I was searching for a function to clone an array but haven't found one. I was curious why PHP doesn't have an array_clone or array_copy function. But then I was nudged into the right direction: Arrays are always assigned by value, not by reference, so it simply doesn't need a clone function because a simple assignment already performs a clone (It's even some sort of deep clone (At least all values inside the array (Arrays are also values, not objects) are copied)). To assign it by reference you have to add an ampersand character:

$arr = array();
$arrClone = $arr; // A clone is created
$arrRef = &$arr; // A reference is created

I really forgot this basic PHP knowledge...

My next problem was: How can I return an array reference from a getter method (I know this is bad practice anyway but I was still curious how this works)? That was a little bit harder. My first try was this:

$arrRef = &$obj->getArray();

But this didn't work, the array was still copied. So my next try was using return &$this->arr in the getter method but this resulted in a syntax error. After searching around a bit I found another lost bit of knowledge: A reference return type can be specified during the function declaration:

function &getArray()
{
    return $this->arr;
}

Unfortunately this alone still didn't work, but the trick is pretty simple: You have to use both solutions together. When the function is declared as return-by-reference then the value is indeed returned by reference but when you don't use an ampersand character on the line where you assign the return value to some variable then the array is copied during the assignment. So the full solution looks like this:

class Test
{
    private $arr = array();

    function &getArray()
    {
        return $this->arr;
    }
}

$obj = new Test();
$arrClone = $obj->getArray(); // A clone is created
$arrRef = &$object->getArray(); // A reference is created

I really should use PHP more often so I stop forgetting the basics...

Posted in PHP | Comments (0)

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.