First of all I'm 90% sure this is me not knowing some basic stuff about how php static methods work, so please forgive my ignorance. I also could not find any info on this on SO, so hopefully this won't be a duplicate.
I'm working on a project with laravel and using the TCPDF-Laravel extension, and I have a footer that needs to say different things based on a condidition:
if ($someCondition) {
$footerText = <<<EOD
text if true
EOD;
} else {
$footerText = <<<EOD
text if false
EOD;
}
PDF::setFooterCallback(function($pdf,$footerText){
$pdf->SetY(-15);
$pdf->Write(0, $footerText, '', 0, 'L', true, 0, false, false, 0);
});
But for some reason, again probably my ignorance, this doesn't run. It says 'too few arguments given', as if $footerText wasn't defined or was null.
I have already tried declaring the variable before the if bracket, declaring the function outside the setFooterCallBack, and using $this->footerText but it didn't work.
CodePudding user response:
Ok to make this simple.
PDF::setFooterCallback()
requires a callable as a first argument. That's where you pass in function($pdf) {}
. In order to expand the functions scope for a variable like $footerText
, you have to use use
to inherit it like so: function($pdf) use($footerText)
.
The reason why you get this error is because you set $footerText
as a second argument after $pdf
, which setFooterCallback
does not know of and therefor, it's not set and calls a too few arguments
exception which is normal.
// outputs "Howdy'ho!"
(function($what) {
echo $what;
})("Howdy'ho!");
// will throw an exception `too few arguments`
(function($what) {
echo $what;
})();
// will output null, because it can be called without an argument.
(function($what = null) {
echo $what;
})();
So theoretically, setting $footerText
to a default null
would work, but this is of course not what you intended to do.
PDF::setFooterCallback(function($pdf, $footerText = null){
$pdf->SetY(-15);
$pdf->Write(0, $footerText, '', 0, 'L', true, 0, false, false, 0);
});
Just inherit the variable $footerText
using use
.
PDF::setFooterCallback(function($pdf) use(footerText) {
$pdf->SetY(-15);
$pdf->Write(0, $footerText, '', 0, 'L', true, 0, false, false, 0);
});