3

So I can push a reference of an object into an array using &

$a = (object) array('a' => 1);
$b[]='test';
$b[] = &$a;
$a->b = 2;
var_dump($b);

Result:

array (size=2)
  0 => string 'test' (length=4)
  1 => &
    object(stdClass)[2]
      public 'a' => int 1
      public 'b' => int 2

But how can I "push" the reference into the start of the array?

I tried

array_unshift($b, &$a);

But I got Fatal error: Call-time pass-by-reference has been removed

1 Answer 1

5

Since it's an object, $a is already (sort of) a reference in itself*. You do not need to dabble with & references at all:

array_unshift($b, $a);

* Objects are unique and not copied on assignment. Changes to an object will be visible across all variables who share the object.

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

1 Comment

I have a better understanding now. And array_push has the same affect which i think is preferable to $b[] = &$a

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.