php动态创建的类对象具有两个具有相同名称的属性,无法找出原因

时间:2018-10-23 07:06:17

标签: php class properties

我以前非常依赖的一些代码现在正在创建一个具有两个具有相同名称的属性的对象。

我认为这甚至不可能拥有两个具有相同名称和单独值的属性。

我有一个将数组转换为类对象的函数。这种方法在许多应用程序中都可以正常工作,而我以前从未遇到过这种固定问题。

下面是添加了var转储和die()的函数,该函数停止执行只是为了获取第一个对象的输出以向大家展示。

params(数组放在下面的put中,类=“ FA \ WheelImage”,命名空间=“”)

new

输出:原始数组,用于键/属性名称的标题,结果类对象。

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;
    }

如您所见,类对象最终以两个名称完全相同的属性结束。这怎么可能? 类对象的定义方式:

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

注意:标题来自csv文件:

namespace FA;


class WheelImage
{
    var $image;
    var $brand;
    var $wheel;
}

1 个答案:

答案 0 :(得分:0)

通过仅创建一个新的csv文件并手动键入csv标题来解决此问题。 原始文件是通过excel保存的。

我的猜测是某种文本编码导致了此问题。

通过删除标题并再次键入来编辑原始文件不起作用,但是创建一个新文件然后将其键入即可解决此问题。

Al-tho我已经解决了我仍然很乐意听到的任何人关于为什么会发生这种情况以及如何使一些通用代码忽略csv文件中任何奇怪的文本编码的想法。

如果我没有重新创建源文件的情况,我认为这可能是一个更好的答案。 Remove non-utf8 characters from string