L
L
litecoin2018-04-15 06:41:56
PHP
litecoin, 2018-04-15 06:41:56

Why is this happening with foreach stdClass in php?

Can you please tell me why, as a result of executing this code, when the value of the $n object changes in the foreach loop , the corresponding value of the $mvs object also changes?

$a = new stdClass();
$b = new stdClass();

$a->name = 'one';
$b->name = 'two';

$movies = new stdClass();
$movies->a = $a;
$movies->b = $b;

foreach ($movies as $mvs) {
  echo $mvs->name.' - before<br />';
  $n = $mvs;
  $n->name = 'changed';
  echo $mvs->name.' - after<br />';
}

but this does not happen in an array (the value of $mvs['name'] remains the same):
$movies = array( 'a' => array( 'name' => 'one'), 'b' => array( 'name' => 'two') );

foreach ($movies as $mvs) {
  echo $mvs['name'].' - before<br />';
  $n = $mvs;
  $n['name'] = 'changed';
  echo $mvs['name'].' - after<br />';
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Camaro67, 2018-04-15
@litecoin

You do not understand how object transfer works, read here , there is an answer to your question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question