I’m trying to get values from a file called input.csv and add it to an object called $myItem. I’m using a foreach method to do so, as you can see. For some reason that is unclear to me, the values of the object are getting mixed up.
When I initially set the value of $item_number using my setter method the value is the correct value – the first entry in the first row of input.csv. However, by the time the foreach loop is completed, the value has changed to the last entry in the first row of input.csv.
This is true for all the instance variables in the object $myItem, they’re all changing to the last entry in the first row of input.csv. I’m not sure why.
Here is my code:
<?php class Item { private $item_number; private $name; private $type; private $make; private $model; private $brand; private $description; // Item Number function SetItemNumber($value) { $this->item_number = $value; } function GetItemNumber() { return $this->item_number; } // Name function SetName($value) { $this->item_number = $value; } function GetName() { return $this->name; } // Type function SetType($value) { $this->item_number = $value; } function GetType() { return $this->type; } // Make function SetMake($value) { $this->item_number = $value; } function GetMake() { return $this->make; } // Model function SetModel($value) { $this->item_number = $value; } function GetModel() { return $this->model; } // Brand function SetDescription($value) { $this->item_number = $value; } function GetDescription() { return $this->description; } // Brand function SetBrand($value) { $this->item_number = $value; } function GetBrand() { return $this->brand; } } $file = fopen("input.csv", "r"); $myItem = new Item; foreach (fgetcsv($file) as $key => $value) { switch ($key) { case 0: $myItem->SetItemNumber($value); echo $myItem->GetItemNumber(); // prints first value in first row of input.csv break; case 1: $myItem->SetName($value); break; case 2: $myItem->SetType($value); break; case 3: $myItem->setMake($value); break; case 4: $myItem->setModel($value); break; case 5: $myItem->setBrand($value); break; case 6: $myItem->setDescription($value); break; } } echo $myItem->GetItemNumber(); // ??? prints last value of first row of input.csv. // This is the value that you should only get from getDescription(). fclose($file); ?>
Thanks in advance for any help!
Advertisement
Answer
Take a look at your setter methods, all of them are doing:
$this->item_number = $value;