Offset object reference to array

So I can push the 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 link to the beginning of the array?

I tried

array_unshift($b, &$a);

      

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

+3


source to share


1 answer


Since it's an object, it's $a

already (sort of) a reference by itself *. You don't need to spoof links at all &

:

array_unshift($b, $a);

      



* Objects are unique and are not copied when assigned. Changes to the object will be visible for all variables that share the object.

+5


source







All Articles