在类之外声明变量并在方法php中访问

时间:2014-08-22 08:30:23

标签: php codeigniter

我使用Codeigniter来构建一些东西。但是当我尝试构建模块打印时,我遇到了问题。我想使用从我的控制器发送的变量。请参阅下面的控制器脚本

public function print_data()
{
    $this->load->library('Pdf');
    $config = $this->config->item('basmalah');
    $data['config'] = $config; //will send data to view
    $this->load->view('/print_laporan_cashdraw',$data);
}

我的观点是这样的

// print_r($config);exit;
$conf = $config;

class MYPDF extends TCPDF {
    //Page header
    public function Header() {

         $this->SetFont('helvetica', '', 12);
         $this->Write(0, 'PT. BASMALAH SIDOGIRI - '.$conf['bas_branch_name'], '', 0, 'C', true, 0, false, false, 0);
         $this->Write(0, $conf['bas_branch_address'], '', 0, 'C', true, 0, false, false, 0);
        // $this->Cell(0, 15, 'PT. BASMALAH SIDOGIRI', 0, false, 'C', 0, '', 0, false, 'M', 'M');
         $style = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '0', 'phase' => 10, 'color' => array(0, 0, 0));
         $this->Line(10, 24, 200, 24, $style);
    }
}

我已使用print_r函数检查了其包含数据,但我无法访问变量

  

$配置

方法标题中的

。我该怎么办?

2 个答案:

答案 0 :(得分:0)

class MYPDF extends TCPDF {
    //Page header
    public function Header() {
         // you have to do this to use global variable.
         global $conf;

         $this->SetFont('helvetica', '', 12);
         $this->Write(0, 'PT. BASMALAH SIDOGIRI - '.$conf['bas_branch_name'], '', 0, 'C', true, 0, false, false, 0);
         $this->Write(0, $conf['bas_branch_address'], '', 0, 'C', true, 0, false, false, 0);
        // $this->Cell(0, 15, 'PT. BASMALAH SIDOGIRI', 0, false, 'C', 0, '', 0, false, 'M', 'M');
         $style = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '0', 'phase' => 10, 'color' => array(0, 0, 0));
         $this->Line(10, 24, 200, 24, $style);
    }
}

答案 1 :(得分:0)

使用以下代码

<?php
    $conf = $config;
    class MYPDF extends TCPDF {
        public $conf = array();
        public function setData($conf){
            $this->conf = $conf;
        }
        //Page header
        public function Header() {
            $this->SetFont('helvetica', '', 12);
            $this->Write(0, 'PT. BASMALAH SIDOGIRI - '.$this->conf['bas_branch_name'], '', 0, 'C', true, 0, false, false, 0);
            $this->Write(0, $this->conf['bas_branch_address'], '', 0, 'C', true, 0, false, false, 0);
            // $this->Cell(0, 15, 'PT. BASMALAH SIDOGIRI', 0, false, 'C', 0, '', 0, false, 'M', 'M');
            $style = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '0', 'phase' => 10, 'color' => array(0, 0, 0));
            $this->Line(10, 24, 200, 24, $style);
        }
    }
    $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->setData($conf);
    ?>