2012-07-25 110 views
1

我正在使用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('SomeString');,并用它里面的类象$this->somestring = $somestringfromoutside

+0

构造函数有什么问题? – 2012-07-25 15:30:54

回答

3

你可以使用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(); 
+1

这就是我所需要的,谢谢你的回答,我不敢相信我没有想到getter/setter方法......谢谢! :) – silentw 2012-07-25 15:40:01

+0

你也是。但是,如果你需要一个真正的getter,你必须重构并暴露'_getProudto()'方法''public''中的'protected'。你也可以在名称中删除'_'前缀,它只是一个Zend命名约定。 – 2012-07-25 16:06:20

1

最好的办法是使用__construct()方法用一个默认参数for $ 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'); 
    } 
} 
0

如果您只专门试图注入$ producto变量。这将是很容易足以让这样的代码中的一个变化:

function Header($producto){ 

这将允许您将参数传递到页眉函数调用。

像这样:

$tfpdf = new tFPDF(); 
$tfpdf->Header($producto); 

如果你真的想在实例化时传递的价值,那么你需要定义一个构造函数,并可能是一个类属性来存储您的$ PRODUCTO值。然后,您将$ producto值传递给构造器并相应地设置属性。然后在你的头文件中你可以引用$ this-> producto而不是$ producto。

相关问题