drdu53813
2015-03-10 13:21 阅读 20
已采纳

php如何在for循环中重新声明类

Im using a library called PDFmerger , naturally, it merges pdfs together. I wish to run a cron every night that builds these to have them ready for the next day. The issue is when I run the code after the first one it fails because it is attempting to redeclare the class.

The for statement...

            foreach ($pdfs_to_build as $pdf) {

                // do stuff

                $this->merge_pdfs($pdf['pdf_id']);

            }

And my pdf merging code that gets ran in the loop...

$pdf = new PDFMerger;

$pdf->addPDF(DIR_BOOKS.$book_path.'/static-pages/page-1.pdf', '1'); 
$pdf->addPDF(DIR_FINAL_PDFS.$pdf_id.'/custom-page-1.pdf','1'); 
$pdf->addPDF(DIR_BOOKS.$book_path.'/static-pages/page-2.pdf', '1'); 

$pdf->merge('file', DIR_FINAL_PDFS.$pdf_id.'/final-build-'.$pdf_id.'.pdf');

Error after the first 1 is complete and we've onto the next one...

Fatal error: Cannot redeclare class PDFMerger in /var/www/example/pdfmerger/PDFMerger.php on line 24

Im wondering is there a workaround for this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    duanci8209 duanci8209 2015-03-10 13:25

    The problem isn't that you're calling new PDFMerger twice, that's perfectly acceptable. The problem is that the file:

    /var/www/example/pdfmerger/PDFMerger.php
    

    Is being include'd (or otherwise executed) twice, which has on line 24:

    class PDFMerger {
    

    That is what is triggering your error, that class has already been declared. Figure out why that file is being included twice and your error will clear up.

    点赞 评论 复制链接分享
  • dongyipa0028 dongyipa0028 2015-03-10 13:29

    Your code is fine. That won't fail. However, not listed in what you posted, you are including PDFMerger.php. Probably by having the include 'PDFMerger.php'; shown at https://pdfmerger.codeplex.com/ run inside the loop.

    Just move that line out of the loop and/or change the include to include_once.

    点赞 评论 复制链接分享

相关推荐