Search code examples
phpclassextend

PHP Unable to set a private variable in an extended class


Trying to extend the FPDF class in PHP with the following code:

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);
        }
    }

I instantiate the class with the variable $pdf and attempt to call the method:

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

I get an internal 500 error....debugging tells me that $reporttitle is an empty property. Can anyone provide me with some insight on how to set variable fields in an extended class? Thanks you.


Solution

  • Don't use the dollar sign to prefix class properties:

                $this->reporttitle = $titlename;
    

    PHP evaluates your $reporttitle first because you used the dollar sign, so you essentially were doing:

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

    To deomonstrate, if you first delcared $reporttitle = 'reporttitle', it would work.


    Also it's worth noting that your variable is not private, it's public because you used the PHP4 var syntax:

    var $reporttitle = 'TEST';
    

    If you want a private variable then use the PHP5 access keyword. Remember that private variables are not accessible to derived classes so if you have a class that extends Reports then reporttitle won't be accessible.

    private $reporttitle = 'TEST';