Some code I used ot rely on a lot is now creating an object with two properties that have the same name.
I did not think this was even possible to have two properties with the same name and separate values.
I have a function that converts an array to a class object. This method has worked fine for so many applications and I have never encountered this stange problem before.
Below is the function with added var dumps and a die() to stop execution just to get the output of the first object to show you guys.
The params (array is putput below, class = "FA\WheelImage", namespace = "")
protected function arrayToClass($array, $class,$nameSpace=''){
$nameSpaceClassPrefix = (!empty($nameSpace))? "\\$nameSpace\\" : "";
if(!class_exists($nameSpaceClassPrefix . $class)){
echo "<br>ERROR: $class is not a valid object type!<br>";
return false;
}
echo "<pre>";
var_dump($array);
var_dump($this->headings);
$class_name = $nameSpaceClassPrefix . $class;
$class_object = new $class_name();
foreach ($array as $key => $value){
//note: this usually only works if the array is associative first so we have to set the key to be the heading
$key = $this->headings[$key];
//only assign if the class object has the property defined. Move out of condition if you the property created regardless of if the model defines it.
if(!$this->explicit_properties || property_exists($class_object, $key)){
if ($value=="false") $value = false;
if ($value=="true") $value = true;
if ($value=="null") $value = null;
$class_object->{$key} = $value;
}
}
var_dump($class_object);
die("stop");
return $class_object;
}
OUTPUT: original array, headings used for key/property names, the resulting class object.
array(3) {
[0]=>
string(14) "TSW_bathurst_1"
[1]=>
string(3) "TSW"
[2]=>
string(8) "Bathurst"
}
array(3) {
[0]=>
string(8) "image"
[1]=>
string(5) "brand"
[2]=>
string(5) "wheel"
}
object(FA\WheelImage)#162 (4) {
["image"]=>
NULL
["brand"]=>
string(3) "TSW"
["wheel"]=>
string(8) "Bathurst"
["image"]=>
string(14) "TSW_bathurst_1"
}
stop
As you can see the class object ends up with two properties with the exact same name. How is this possible? How the class object is defined:
namespace FA;
class WheelImage
{
var $image;
var $brand;
var $wheel;
}
NOTE: The headings are coming from a csv file:
//the csv file
image,brand,wheel
TSW_bathurst_1,TSW,Bathurst
TSW_bathurst_2,TSW,Bathurst
TSW_bathurst_3,TSW,Bathurst
TSW_bathurst_4,TSW,Bathurst
//how the headings are loaded
if ($has_headings) $this->headings = fgetcsv($file);//first row is headings