2014-01-27 165 views
1

下面是我在做什麼:PHP - 更新公共變量

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

looplimitrows總是返回,而不是我想行。 我是不是做對了?

這裏的類:

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() 

} 

回答

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 
0

您所呼叫的loopContents()方法,無需先設置公共變量looplimitrows。因此該方法的默認值爲looplimitrows。首先設置looplimitrows公共變量並調用loopContents()方法。