Search code examples
phpclassvariablestcpdfextend

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!


Solution

  • Take a look at $GLOBALS variables here is a example

    <?php
    $a = 1;
    $b = 2;
    
    function Sum()
    {
        $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
    } 
    
    Sum();
    echo $b;
    ?>
    

    More on Variables scopes here