2012-12-26 35 views
0

試圖在PHP用下面的代碼擴展FPDF類:PHP無法設置爲私有變量在擴展類

class Reports extends FPDF{ 

     var $reporttitle = 'TEST'; 

     function settitle($titlename){  
      $this->$reporttitle = $titlename; 
     } 
     function header(){ 
      $this->SetMargins(.5,.5); 
      $this->Image('../../resources/images/img028.png'); 
      $this->SetTextColor(3,62,107); 
      $this->SetFont('Arial','B',14); 
      $this->SetY(.7); 
      $this->Cell(0,0,$this->$reporttitle,0,0,'R',false,''); 
      $this->SetDrawColor(3,62,107);   
      $this->Line(.5,1.1,10,1.1); 
     } 
    } 

我實例化變量$ PDF類,並試圖調用方法:

$pdf = new Reports('L','in','Letter'); 
    $pdf-> settitle('Daily General Ledger'); 
    $pdf->AddPage();  

我得到一個內部500錯誤....調試告訴我$ reporttitle是一個空屬性。任何人都可以提供一些關於如何在擴展類中設置變量字段的見解嗎?謝謝。

回答

3

不要使用美元符號前綴類屬性:

  $this->reporttitle = $titlename; 

PHP評估您的$reporttitle首先是因爲你使用了美元符號,所以你基本上是這樣做的:

$this-> = $titlename; 
// ^nothing 

要deomonstrate,如果你先delcared $reporttitle = 'reporttitle',它會工作。如果你想那麼一個私有變量使用PHP5連接關鍵詞

var $reporttitle = 'TEST'; 


另外值得注意的是你的變量不是私有的,因爲你使用了PHP4 var語法,這是公開的。請記住,私有變量是不是派生類訪問,所以如果你有一個延伸的類Reports然後reporttitle將無法​​訪問。

private $reporttitle = 'TEST'; 
+0

我原本是把它設置爲私有的 - 我正在愚弄代碼,試圖找出錯誤。我已將其重新設置爲私密。謝謝,MrCode! – user1532602

+0

@ user1532602沒問題:) – MrCode

1
$this->$reporttitle = $titlename; 

應該是:

$this->reporttitle = $titlename;