Reputation: 1368
I'm using FPDF to export channel data from ExpressionEngine to a PDF file. The FPDF-stuff I'm using is code I used in another project before, so it should work. Normal methods of the FPDF-object work, but as soon as they get wrapped in a function I get:
Fatal error: Call to a member function MultiCell() on a non-object
So this works:
include '../apps/assets/fpdf.php';
// setup the PDF object:
$pdf = new FPDF();
$pdf->SetMargins(0,0,0);
$pdf->SetAuthor("Author");
$pdf->addPage("P", "A4");
$pdf->SetTextColor(82,82,82);
// write something to the PDF:
$pdf->MultiCell(80, 6, "some text here", 0, "L");
But this doesn't:
include '../apps/assets/fpdf.php';
// setup the PDF object:
$pdf = new FPDF();
$pdf->SetMargins(0,0,0);
$pdf->SetAuthor("Author");
$pdf->addPage("P", "A4");
$pdf->SetTextColor(82,82,82);
writeStuff("some stuff to write");
function writeStuff($stuff) {
global $pdf;
$pdf->MultiCell(80, 6, $stuff, 0, "L");
}
The last block of code throws the error as posted above.
It's weird, because the exact same setup did work before. The main difference is that this time, the PHP is wrapped in an ExpressionEngine template. The template does have PHP-parsing enabled and I'm using a buch of other templates in the same application with lots of PHP in it that do work.
Does it have to do with the parsing-order of ExpressionEngine? Is the method 'writeStuff' being called before the $pdf object is created?
Any ideas?
Upvotes: 2
Views: 7214
Reputation: 420
The problem is that php in EECMS templates are run using eval(). This means that your php is being run in local scope. So you'll have to use the GLOBAL keyword on variables inside and outside of your function definition.
Example:
<?php
global $foo;
$foo = 'Hello World!';
bar();
function bar() {
global $foo;
echo $foo;
}
?>
So for your template, just change it to the following:
include '../apps/assets/fpdf.php';
// setup the PDF object:
global $pdf;
$pdf = new FPDF();
There used to be a great KB article, but it seems like it's gone now. I was able to get a wayback archive of the original:
Hope that helps!
Upvotes: 3