PHP - 更新公共变量

时间:2014-01-27 11:50:03

标签: php class variables

这就是我正在做的事情:

<?php
$csvObj = new Csv2Parser($file);
$csvObj->loopContents();
$csvObj->looplimitrows = 9; // why does this get ignored?
?>

looplimitrows 始终返回 5 行,而不是我想要的 9 。 我做得不对吗?

这是班级:

class Csv2Parser
{
    private $filepath; 

    public $looplimitrows = 5; 

    /*
      .... __construct() goes here...
    */

    public function loopContents(){
      $looplimitrows = $this->looplimitrows;
      $linecount=0;
      $fp = fopen($targetFile, "r"); // open the file
      while ($line = fgetcsv($fp)) {
      $linecount++;

        if(!empty($looplimitrows) && $linecount > $looplimitrows){ break; }

        echo $line[0]; // first column only

      }//eof while()

}

2 个答案:

答案 0 :(得分:3)

它被忽略了,因为它没有在你循环通过csv之前设置,因为限制是5,因为它是默认值。

public $looplimitrows = 5;

您需要设置Csv2Parser::looplimirows,如下所示。

$csvObj = new Csv2Parser($file);
$csvObj->looplimitrows = 9; // It needs to go here.
$csvObj->loopContents();

或者,试试这个:)

<?php
ini_set('auto_detect_line_endings', true);

class Csv2Parser {

    private $rowLimit = NULL;

    private $fileHandle = NULL;
    private $data = NULL;

    public function __construct($filename) 
    {

        if (!file_exists($filename))
            throw new Exception("Can't find file:" . $filename);

        $this->fileHandle = fopen($filename, "r");
    }


    public function get($n) 
    {
        $this->rowLimit = (int) $n;

        return $this;
    }


    public function rows()
    {
        $linecount = 0;

        while (($line = fgetcsv($this->fileHandle, 1000, ",")) !== false) {
            $linecount++;

            if(!is_null($this->rowLimit) && $linecount > $this->rowLimit)
                break;


            $this->data[] = $line;

        }

        return $this->data;
    }
}


$csv = new Csv2Parser("my.csv");
print_r($csv->get(9)->rows()); // Could not be more self explanitory

答案 1 :(得分:0)

您在没有先设置公共变量loopContents()的情况下调用looplimitrows方法。因此,该方法使用默认值looplimitrows执行。首先设置looplimitrows公共变量并调用loopContents()方法。