text: Q:
  
  Array overwritten after foreach loop
  
  I'm trying to push objects containing elements from a sql result set into an array. My code is like:
  $data = array();
  $sql = "SELECT id,type,name,username FROM users";
  foreach ($conn->query($sql) as $row) { 
      $this->set_id($row['id']);
      $this->set_type($row['type']);
      $this->set_username($row['username']);
      $this->set_password($row['password']);
  
      $data[] = $this;
  }
  
  My resultset is correct but I get my array cells overwritten with values from the last recordset after the foreach loop ends. For example, if I have these results {1,'type1','user','pass'}, {2,'type2','foo','bar'}, when I print_r my $data array ouside of the loop, I get only the second resultset repeated twice. What am I doing wrong?
  
  A:
  
  Inside an instance method, $this always refers to the current class instance; at every loop iteration you modify the instance itself and then add it to $data; but at the point of assignment a copy is not made and a reference to the same instance is added instead.
  In the end you have an array with the same object at each index.
  You would need to create a new instance of the class you're in at every loop iteration:
  foreach ($conn->query($sql) as $row) { 
      $obj = new self; // create new instance of ourselves
  
      $obj->set_id($row['id']);
      $obj->set_type($row['type']);
      $obj->set_username($row['username']);
      $obj->set_password($row['password']);
  
      $data[] = $obj;
  }
  
  This is a personal suggestion, but I would either move this code inside a static method or a separate class altogether.
  
  