简体   繁体   中英

How can I pass PHP class data to another class within $this?

I'm trying to build an OOP PHP Invoice-script. I'd like to output the data to an PDF, so I'm using FPDF. I create this object within a method of the invoice-class like this:

public function renderPDF() {

        require("pdf.class.php");

        $this->invoicePDF = new PDF();

        $this->invoicePDF->AddPage();
        $this->invoicePDF->SetFont('Helvetica','',12);


        //build PDF
    }

This method and it's call work perfectly when testing with static data within pdf.class.php. But how can I use the data of $this (the invoice-class) inside of the pdf-class?

I've tried passing $this in the creation of new PDF($this) and calling it inside a __construct. Is this the way? It threw an FDPF error/warning: Warning: count(): Parameter must be an array or an object that implements Countable

For full disclosure, the pdf.class.php (there's Dutch comments between the lines):

require('fpdf181/fpdf.php');
include("fpdf181/font/helvetica.php");
include("fpdf181/font/helveticab.php");
include("fpdf181/font/helveticabi.php");
include("fpdf181/font/helveticai.php");


class PDF extends FPDF
{
    private $invoiceData;
    function __construct($invoiceClass) {
        $this->invoiceData = $invoiceClass;
    }
    //Page header
    function Header()
    {
        //Logo
        $this->Image('../img/icon-192-circle.png',10,8,33);
        //Arial vet 15
        $this->SetFont('Helvetica','B',15);
        //Beweeg naar rechts
        $this->Cell(80);
        //Titel
        $this->Cell(30,10,'Factuur',0,0,'C');

        $this->Cell(30,10,$this->invoiceData->getInvoiceDate(),0,0,'C');
        //Line break
        $this->Ln(20);
    }

    //Page footer
    function Footer()
    {
        //Positie 1.5 cm van de onderkant
        $this->SetY(-15);
        //Arial cursief 8
        $this->SetFont('Arial','I',8);
        //Pagina nummer
        $this->Cell(0,10,'Gelieve binnen 14 dagen overmaken op IBAN: INGB 12345678910 onder vermelding van factuurnummer.',0,0,'C');
    }
}

I've searched Stackoverflow for the answer, read the documentation of FPDF, but did not find an answer that's suitable for me. Hope someone can help or point me in the right direction!

You are overwriting FPDF's default constructor, which is incompatible with the parameters you are passing to your own constructor.

Either call the parent constructor inside your own constructor with the correct parameters, or use another function after instantiating your class, like so:

$this->invoicePDF = new PDF();
$this->invoicePDF->setInvoiceData($this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM