尝试用以下代码在PHP中扩展FPDF类:
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是一个空属性。有人能为我提供一些关于如何在扩展类中设置变量字段的见解吗?谢谢你。
不要使用美元符号作为类属性的前缀:
$this->reporttitle = $titlename;
PHP首先评估你的$reporttitle
,因为你使用了美元符号,所以你基本上是在做:
$this-> = $titlename;
// ^ nothing
要取消演示,如果您首先删除$reporttitle = 'reporttitle'
,它会起作用。
另外值得注意的是,您的变量不是私有的,而是公共的,因为您使用了PHP4var
语法:
var $reporttitle = 'TEST';
如果您想要一个私有变量,请使用PHP5访问关键字。请记住,私有变量对派生类是不可访问的,因此如果您有一个扩展Reports
的类,则reporttitle
将不可访问。
private $reporttitle = 'TEST';
$this->$reporttitle = $titlename;
应该是:
$this->reporttitle = $titlename;