循环时出现数组对象问题

I am getting only the last value while executing the below code. Please help me to get the correct values.

$formJsonMemData = (object) array();
$array_member = array();

echo'<pre>';
for($i=0;$i<10;$i++)
{
$formJsonMemData->i = $i;
$array_member[]=$formJsonMemData;

}

print_r($array_member);

Current output

[1] => stdClass Object
    (
        [i] => 4
    )

[2] => stdClass Object
    (
        [i] => 4
    )

[3] => stdClass Object
    (
        [i] => 4
    )

[4] => stdClass Object
    (
        [i] => 4
    )

I need it to be printed like

[1] => stdClass Object
    (
        [i] => 1
    )

[2] => stdClass Object
    (
        [i] => 2
    )

[3] => stdClass Object
    (
        [i] => 3
    )

[4] => stdClass Object
    (
        [i] => 4
    )

You can redefine the object at each iteration

$array_member = array();

echo'<pre>';
for($i=0;$i<10;$i++){
    $formJsonMemData = (object) array();
    $formJsonMemData->i = $i;
    $array_member[$i] = $formJsonMemData;
}

print_r($array_member);

What you are seeing is the difference between by reference and by value.

When you set a variable (or array element) to equal a property of an object, you’re really saying you want it to be whatever the value is right now, not what it was when it was assigned.

To get the behavior you’re expecting, the content of the property must be passed by value, not by reference. A getter method would do this:

class formJsonMemData {
  private $i;

  public function __construct() {

  }

  public function set_i($i) {
    $this->i = $i;
  }

  public function get_i() {
    return $this->I;
  }
} 


$array_member = array();
$f = new formJsonMemData;

for($i=0;$i<10;$i++)
{
  $f->set_i($i); 
  $array_member[]=$f->get_i();

}

print_r($array_member);

On the first line of your code, you create an object and assign it to $formJsonMemData. Your code then runs through a loop and sets the i property of the object on each iteration before adding it to your array, $array_member.

The problem you have is that objects are passed by references by default. You're setting the value of i on each iteration but all the elements in your array point to the same object. At the end of your loop, you don't have 10 objects, each with their own value for i. You have the same object 10 times that has been updated on each iteration.

It's unclear what the goal of your code is which makes it difficult to suggest how best to resolve this. If you want an array of objects, each with their own i property, then you need a new instance on each iteration of the loop.

Example:

$array_member = array();

for ($i = 0; $ < 10; $i++) {
    $new_object = new stdClass();
    $new_object->i = $i;
    $array_member[] = $new_object;
}

Further reading: https://www.php.net/manual/en/language.oop5.references.php