2

Is there a way to create a PHP array which always treated by reference without having to use the & operator?

For instance:

$a = array_by_ref('a', 'b', 'c');
$b = $a;
$b[] = 'd';

should result in both $a and $b being equal to:

('a', 'b', 'c', 'd')
2
  • 1
    Using the & symbol involves less typing :) Commented Dec 31, 2010 at 18:48
  • 1
    Personally, I'd suggest against doing anything to get around the usage of the & operator, mostly for code readability. Using & makes it obvious that you're dealing with a reference. Remove it (using any method) could potentially cause confusion to others reading your code (and even sometimes yourself given that there's a length of time from writing to re-reading.. Not that that's ever happened to me of course ;)) Commented Dec 31, 2010 at 19:09

2 Answers 2

1

If SPL is available, there is the ArrayObject class:

$a = new ArrayObject(array('a', 'b', 'c'));
$b = $a;
$b[] = 'd';

These are still wrapper objects though; to get their primitive array equivalents you have to use the object's getArrayCopy() method. Also bear in mind that it can be quite slow, particularly when you iterate through its elements.

Sign up to request clarification or add additional context in comments.

2 Comments

I think ArrayObject::getArrayCopy() might be preferable to casting.
@Mchl: Thanks for catching that.
0

ArrayObject doesn't go along with array_map, array_reduce, and similar functions that expect a real array as an input. If you want an array property of an object to be copied by reference, wrap it with any kind of object:

class Test
{
    private $array;

    public function __construct()
    {
        $this->array = (object) ['array' => []];
    }

    // we also need to return it by reference
    public function &getMyArray()
    {
        return $this->array->array;
    }
}

Sample usage:

$test = new Test();
$test->getMyArray()[] = 'Hello';
$another = clone $test;
$another->getMyArray()[] = 'Fucking';
$third = clone $another;
$third->getMyArray()[] = 'World!';
unset($test->getMyArray()[1]);

var_dump($test->getMyArray() === $third->getMyArray());
var_dump(implode(" ", $test->getMyArray()));
var_dump(gettype($test->getMyArray()));

Sample output:

bool(true)
string(12) "Hello World!"
string(5) "array"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.