2014-10-29 58 views
1

我正在使用TCPDF來創建獎勵生成器。 它檢查獎,它在IMAGE_PATH變量填充型基礎上(這一點關係都沒有這個問題的一些其他變量。PHP在擴展類中使用外部變量

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

稍遠一點,在TCPDF的example_051看到他們延長類來定義的背景圖片。 於該圖像的路徑是一個是在上面創建的變量$ img_file。

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

由於變量$ IMAGE_FILE沒有內延伸已知的範圍。是有一種方法可以使這項工作?

提前致謝!

回答

0

看看$GLOBALS變量 這裏是一個例子

<?php 
$a = 1; 
$b = 2; 

function Sum() 
{ 
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; 
} 

Sum(); 
echo $b; 
?> 

更多關於變量的範圍here

+0

在這個類的變量的擴展通過$ GLOBALS [ 'img_file']代替$ img_file後仍然是空的 即模具($ GLOBALS [ 'img_file']);在擴展結束時。 – Yentel 2014-10-29 16:02:57

1
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); 
+0

不知何故,這會導致TCPDF錯誤:空字體家族 http://pastebin.com/8DekH7KL – Yentel 2014-10-29 16:09:52

+0

您可能需要調用父構造函數。 – Evert 2016-07-10 07:21:51

0

你需要讓變量$ img_file一個全球性的函數內部使用。 這就需要功能 手冊裏面這裏需要做: http://php.net/manual/en/language.variables.scope.php

public function Header() { 
    global $img_file; 
    // get the current page break margin 
    $bMargin = $this->getBreakMargin(); 

    ... 
0

這爲我工作。

class MYPDF extends TCPDF { 
    private $data = array(); 

    public function setData($key, $value) { 
    $this->data[$key] = $value; 
    } 

    public function Header() { 
    $this->data['invoice_no']; 
    .... 
    } 
}  
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); 
$pdf->setData('invoice_no', $invoice_no);