php对象上的空数组属性

php对象上的空数组属性,php,Php,这是我的类,它读取csv并以某种方式存储信息 <?php class CSV{ private $data; function __construct($filename){ $this->data = $this->getDataFromFile($filename); } public function __get($property){ if(pr

这是我的类,它读取csv并以某种方式存储信息

<?php
    class CSV{
        private $data;

        function __construct($filename){
            $this->data = $this->getDataFromFile($filename);
        }

        public function __get($property){

            if(property_exists($this,$property)){
                return $this->$property;
            }
        }



        private function getDataFromFile($filename){
            $new_data = array();
            $result = array();
            if (($handle = fopen($filename,"r")) !== FALSE) {
                while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
                    array_push($result, explode(";", $data[0]));;
                }
                fclose($handle);
            }


            $header = $result[0];

            $in_columns = array();
            for ($j = 0 ; $j < count($result[0]); $j++){
                $new = array();
                for ($i = 1 ; $i < count($result); $i++){
                    array_push($new, $result[$i][$j]);
                }
                array_push($in_columns, $new);
            }

            $idx = 0;
            foreach ($header as $title) {
                $new_data[$title] = $in_columns[$idx];
                $idx++; 
            }
            //var_dump($new_data);//the content of $new_data its correct
            $this->data = $new_data;
        }
    }

?>

最后一个var_dump显示了一个空值?值的赋值有什么问题吗?对我来说似乎是正确的,问题出在哪里了???

您在构造函数中调用
$this->getDataFromFile($filename)
,并将其值赋值给
$this->data
。 然而。。。
getDataFromFile()
的实现实际上没有返回任何值,因此它将
NULL
赋值给该属性

您需要更改
getDataFromFile()
以返回值 去掉构造函数中的变量赋值-
$this->data
已在方法中设置

关于
\u get()
- 这是一个好主意。它检查指定的属性是否存在,如果存在,则返回其值。你不会这么说的。使用以下代码(将
$this->data
公开后):


为此属性准备访问器,该访问器将返回此值。

问题是您的CSV文件以空行结尾(
\n
在最后一行之后)


因此,您正在处理一个空数组,将一个单位化变量(null)推入数据数组。

但是
$csv->data
它是私有的,然后准备一个访问器,如
getData()
,在那里您将返回此属性或将其公开。实际上,与
getData()
的结果相同。。。等待在构造函数中调用
$this->getDataFromFile($filename)
并将其值赋给
$this->data
。然而。。。您的
getDataFromFile
实现根本没有返回任何值,因此它赋值为NULL。为什么不尝试使用
$this->data=$this->getDataFromFile($filename)设置一些简单的测试它是否正确填充,如
$this->data=array('test1','test2')
$csv = new CSV('./csv/file.csv');
var_dump($csv->__get('data'));
var_dump($csv->data);