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

我可以在函数中使用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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀