[英]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.