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条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵