dongzhiyong8577 2015-12-12 09:40
浏览 59
已采纳

我可以在函数中使用php“require_once”来阻止PHPMailer加载直到我需要它吗?

I could include the PHPmailer library automatically, but it seemed leaner to me to only load it when I need to actually send an e-mail. I'm using a custom "send an email" function which can be called from any page on my site so it seems inefficient to try and include PHPmailer based on which pages use mail.

If I can just put a "require_once("PHPmailer.php");" statement in my send mail function, what happens? Does it work as I expect and load PHPmailer just one time on the first call per session or is it uglier than that?

  • 写回答

2条回答 默认 最新

  • douhanxujiuji6098 2015-12-12 09:48
    关注

    Short answer: Yes, you can.

    But there is even a better way! You get your PHP files to be included automatically when you instantiate the class that is defined in that file. This is called autoloading. [Wikipedia]. Just to bring you and other PHP developers up to speed with best practices in modern PHP development; Take a look at composer and Dependency Injection. It provides a way to lazy load services so that they only get loaded when you need them.

    With Composer all your dependencies will be managed and an autoloader will be created magically. You just need to put a single require_once __DIR__ . '/vendor/autoload.php';' at the top of your code and from that point on, whenever you do new PhpMailer for the first time it requires the PHPMailer class file. See the PHPMailer documentation for how to install PHPMailer using Composer.

    It might seem a lot of work, compared to just typing require_once before any call to the PHPMailer, but in the long run, when your project grows, you will profit!

    I also encourage you to read the above link on Dependency Injection since that might help you to even better decouple and structure your code. A good container to get started with might be PHP-DI. Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 matlab简单代码修改补充
  • ¥15 python提取.csv文件中的链接会经常出现爬取失败
  • ¥15 数据结构中的数组地址问题
  • ¥15 maya的mel里,怎样先选择模型A,然后利用mel脚本自动选择有相同名字的模型B呢。
  • ¥15 Python题,根本不会啊
  • ¥15 会会信号与系统和python的来
  • ¥15 关于#python#的问题
  • ¥20 oracle RAC 怎么配置啊,配置
  • ¥15 excel 日常使用中出现问题
  • ¥20 pdusession建立失败