我正在使用TCPDF制作奖励生成器。 它会检查奖励的类型,并根据它填写image_path变量(以及与此问题无关的其他一些变量。
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 :(得分: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);
答案 1 :(得分:0)
查看$GLOBALS
个变量
这是一个例子
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
有关变量范围的更多信息here
答案 2 :(得分: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();
...
答案 3 :(得分: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);