PHP использует внешнюю переменную в расширяющем классе

Я использую 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 ...
}

Чуть дальше, как видно из example_051 в TCPDF, они расширяют класс для определения фонового изображения.
Путь к этому изображению находится в переменной $ 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 неизвестна в пределах расширения. Есть ли способ, которым я мог бы сделать эту работу?

Заранее спасибо!

1

Решение

Взгляни на $GLOBALS переменные
вот пример

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

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

Sum();
echo $b;
?>

Подробнее об областях действия переменных Вот

0

Другие решения

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

Вам нужно сделать переменную $ 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);
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector