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

0

I've created a helper to organize the menus returned from the database so that it looks similar to a return of a native method of the framework I'm using. The code snippet that contains 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 But what's coming in the final variable is this In other words, he is overwriting the first position with the second, why is this happening? What's wrong with the code?

    
asked by anonymous 11.04.2018 / 22:22

1 answer

1

Since you are creating the $obj instance out of the repeat loop, you will have the same reference in all iterations, overwriting the old values. This overwrite is mirrored into the array $menu because PHP appends the array to the object's own reference, not a copy of it. To solve, you have two solutions: 1) instantiate the object inside the loop; 2) insert a copy of the object into the array .

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 at 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 at Repl.it

    
11.04.2018 / 22:32