Search code examples
phpclassthis-pointer

PHP Class properties being overwritten when I store to array


There is probably a very simple explanation for this, but I've had this code working for months, and now all of a sudden today it doesn't work.

I retrieve all the rows from a table. I have and object which is an entity model of the table I'm selecting from. As I read the rows from the associative result array, I'm storing each property using "$this->propertyName," and then I'm pushing each object to an array. Before I ended up with an array of objects, now I end up with an array of the same object repeated. Here's a code snippet:

     $mdSelectALL_sql="SELECT * FROM member_data";

     $mdSelectALL=mysql_query($mdSelectALL_sql,$mdConn);

     if(!$mdSelectALL){
            die('Error: ' . mysql_error());
     }
     else{
            echo "RETURNING ALL MEMBER DATA RECORDS!!!<br>";

            //store all records into array
            while($row=mysql_fetch_array($mdSelectALL))
            {


                    $this->mdId=$row['md_id'];
                    $this->mdFname=$row['md_fname'];
                    $this->mdLname=$row['md_lname'];
                    $this->mdEmail=$row['md_email'];
                    $this->mdTwitter=$row['md_twitter'];
                    $this->mdFacebook=$row['md_facebook'];
                    $this->mdMyspace=$row['md_myspace'];
                    $this->mdPhoneNumber=$row['md_phonenumber'];
                    $this->mdNotes=$row['md_notes'];



                    //store records in array
                    array_push($mdArray,$this);

           }//end while

           // print_r($mdArray); prints the array and each element is the last record  encountered in the SQL retrieval

            return $mdArray;

            }//end else

My getters and setters look like this for each property:

       function get_mdId(){
              return $this->mdId;
       }

       function set_mdId($id){
             $this->mdId=$id;
       }

And suggestions or ideas?

-TU


Solution

  • Objects are passed around by reference. That means that when you change a value, that value will change everywhere that you have used that object.

    As you are storing the same object every time - $this - you end up with an array of references to the same object.

    To solve it, you can do:

    $mdArray = array();
    while($row=mysql_fetch_array($mdSelectALL))
    {
       $tmp_object = new MyObject;   // fill in the name of your object...
    
       $tmp_object->mdId=$row['md_id'];
       ...
    
       array_push($mdArray, $tmp_object);
    }