Array of objects in php, objects being overwritten, why?

Asked

Viewed 38 times

0

I created a helper to organize the menus returned from the database in a way that is similar to a return of a native method of the framework I am using. The code snippet containing the error is this:

$obj = new \stdClass;
$menu =  array();

for($i=0; $i<count($menus_aceitos_name); $i++){ 
        $obj->name = $menus_aceitos_name[$i];
        $obj->id  = $menus_aceitos_id[$i];
        $menu[$i] = $obj;
    }

I debugged and the expected result would be this inserir a descrição da imagem aqui But what’s coming in the final variable is this inserir a descrição da imagem aqui In other words, he’s overwriting the first position with the second, why is this happening? What’s wrong with the code?

1 answer

1


How is creating the instance $obj outside the loop, you will have the same reference in all iterations, overriding the old values. This envelope is mirrored into the array $menu because PHP adds to array the object’s own reference and not a copy of it. To solve, you have two solutions: 1) instantiate the object within the loop; 2) insert into the array a copy of the object.

Sample code for solution 1:

$lista = [];

for ($i = 0; $i < 2; $i++) {
  $obj = new stdClass;
  $obj->id = $i;
  $lista[] = $obj;
}

print_r($lista);

See working on Repl.it

Sample code for solution 2:

$obj = new stdClass;
$lista = [];

for ($i = 0; $i < 2; $i++) {
  $obj->id = $i;
  $lista[] = clone $obj;
}

print_r($lista);

See working on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.