[英]Undefined variable when I try to pass array to a class which extends another one
[英]Pass variable to a class which extends another one
我正在使用tFPDF類。
我正在使用此代碼擴展此類以獲取自定義頁眉和頁腳
class PDF extends tFPDF{
function Header(){
$this->Image('../../images/logo-admin.png',10,6,30);
$this->SetFont('DejaVu','',13);
$this->Cell(247,10,$produto,0,0,'C',false);
$this->SetDrawColor(0,153,204);
$this->SetFillColor(98,197,230);
$this->SetTextColor(255);
$this->Cell(30,10,date('d/m/Y'),1,0,'C',true);
$this->Ln(20);
}
function Footer(){
$this->SetY(-15);
$this->SetFont('Arial','',8);
$this->Cell(0,10,'P'.chr(225).'gina '.$this->PageNo().'/{nb}',0,0,'C');
}
}
我需要做的是以某種方式用一個不屬於該類的變量來改變$produto
。
我用$pdf = new PDF();
來調用這個類$pdf = new PDF();
。
我怎樣才能將一個變量傳遞給這個類,所以我可以使用一個字符串,比如$pdf = new PDF('SomeString');
並在類中使用它,如$this->somestring = $somestringfromoutside
您可以使用protected
var並聲明一個setter。
class PDF extends tFPDF {
protected $_produto = NULL;
public function Header(){
/* .. */
$this->Cell(247,10,$this->_getProduto(),0,0,'C',false);
/* .. */
}
public function Footer(){
/* .. */
}
public function setProduto($produto) {
$this->_produto = $produto;
}
protected function _getProduto() {
return $this->_produto;
}
}
// Using example
$pdf = new PDF();
$pdf->setProduto('Your Value');
$pdf->Header();
最好的辦法是使用__construct()方法和$ myString的默認參數
class PDF extends tFPDF{
public $somestring;
function __construct($myString = '') {
parent::__construct();
$this->somestring = $myString;
}
function Header(){
$this->Image('../../images/logo-admin.png',10,6,30);
$this->SetFont('DejaVu','',13);
$this->Cell(247,10,$produto,0,0,'C',false);
$this->SetDrawColor(0,153,204);
$this->SetFillColor(98,197,230);
$this->SetTextColor(255);
$this->Cell(30,10,date('d/m/Y'),1,0,'C',true);
$this->Ln(20);
}
function Footer(){
$this->SetY(-15);
$this->SetFont('Arial','',8);
$this->Cell(0,10,'P'.chr(225).'gina '.$this->PageNo().'/{nb}',0,0,'C');
}
}
如果你特意只是嘗試注入$ producto變量。 在代碼中進行一次更改很容易,如下所示:
function Header($producto){
這將允許您將參數傳遞給Header函數調用。
像這樣:
$tfpdf = new tFPDF();
$tfpdf->Header($producto);
如果你真的想在實例化時傳遞值,那么你需要定義一個構造函數,可能還有一個類屬性來存儲你的$ producto值。 然后,您將$ producto值傳遞給構造函數並相應地設置屬性。 然后在您的標題函數中,您將引用$ this-> producto而不是$ producto。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.