Yentel Yentel - 4 months ago 12
PHP Question

PHP use an external variable in an extending class

I'm using TCPDF to make an award generator.
It checks the type of award and based on that it fills in the image_path variable (and some other variables that had nothing to do with this question.

switch($award){
case 25:
$img_file = '../../img/award_25.png';
break;
case 50:
$img_file = '../../img/award_50.png';
break;
... and so on ...
}


A little further, as seen in example_051 of TCPDF they extend the class to define the background image.
The path to that image is the one that is in the variable $img_file created above.

require_once('tcpdf_include.php');
class MYPDF extends TCPDF {
public function Header() {
// get the current page break margin
$bMargin = $this->getBreakMargin();
// get current auto-page-break mode
$auto_page_break = $this->AutoPageBreak;
// disable auto-page-break
$this->SetAutoPageBreak(false, 0);
// margins Left, Top, Right, Bottom in pixels
$this->Image($img_file, -9, -8, 316, 225, '', '', '', false, 300, '', false, false, 0);
// restore auto-page-break status
$this->SetAutoPageBreak($auto_page_break, $bMargin);
// set the starting point for the page content
$this->setPageMark();
}
}


Due to the scope the variable $image_file is not known within the extend. Is there a way I could make this work?

Thanks in advance!

Answer
class MYPDF extends TCPDF {
protected $img_file;
 public function __construct($img_file)
    {
        $this->img_file = $img_file;
    }
    public function Header() {
        // get the current page break margin
        $bMargin = $this->getBreakMargin();
        // get current auto-page-break mode
        $auto_page_break = $this->AutoPageBreak;
        // disable auto-page-break
        $this->SetAutoPageBreak(false, 0);
        // margins Left, Top, Right, Bottom in pixels
        $this->Image($img_file, -9, -8, 316, 225, '', '', '', false, 300, '', false, false, 0);
        // restore auto-page-break status
        $this->SetAutoPageBreak($auto_page_break, $bMargin);
        // set the starting point for the page content
        $this->setPageMark();
    }
}
$MYPDF = new MYPDF($img_file);