我可以在函数中使用 php "require_once" 来阻止 PHPMailer 在我需要它之前加载吗?
Can I use php "require_once" in a function to prevent PHPMailer from loading until I need it?
我可以自动包含 PHPmailer 库,但仅在我需要实际发送电子邮件时加载它对我来说似乎更精简。我正在使用自定义 "send an email" 函数,可以从我网站上的任何页面调用它,因此尝试根据哪些页面使用邮件来包含 PHPmailer 似乎效率不高。
如果我可以放一个 "require_once("PHPmailer.php");"在我的发送邮件功能中声明,会发生什么?它是否像我预期的那样工作并在每个会话的第一次调用时只加载一次 PHPmailer 还是比那更丑陋?
简短回答:可以。
但还有更好的方法! 当您实例化其中定义的 class 时,您的 PHP 文件会自动包含在内文件。 这称为自动加载。 [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。它提供了一种延迟加载服务的方法,以便它们仅在您需要时才加载。
使用 Composer,您的所有依赖项都将得到管理,自动加载器将神奇地创建出来。您只需要在代码的顶部放置一个 require_once __DIR__ . '/vendor/autoload.php';'
,从那时起,每当您第一次执行 new PhpMailer
时,它都需要 PHPMailer class文件。请参阅 how to install PHPMailer using Composer 的 PHPMailer 文档。
与在任何调用 PHPMailer 之前仅键入 require_once 相比,这看起来工作量很大,但在长 运行,当你的项目做大了,你就会盈利!
我还鼓励您阅读上面 link 中有关依赖注入的内容,因为这可能会帮助您更好地解耦和构建代码。一个好的入门容器可能是 PHP-DI。祝你好运!
可以的
require_once();
将只包含文件一次。其余时间调用它只会 return true(文件是否存在无关紧要)。
The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.
我可以自动包含 PHPmailer 库,但仅在我需要实际发送电子邮件时加载它对我来说似乎更精简。我正在使用自定义 "send an email" 函数,可以从我网站上的任何页面调用它,因此尝试根据哪些页面使用邮件来包含 PHPmailer 似乎效率不高。
如果我可以放一个 "require_once("PHPmailer.php");"在我的发送邮件功能中声明,会发生什么?它是否像我预期的那样工作并在每个会话的第一次调用时只加载一次 PHPmailer 还是比那更丑陋?
简短回答:可以。
但还有更好的方法! 当您实例化其中定义的 class 时,您的 PHP 文件会自动包含在内文件。 这称为自动加载。 [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。它提供了一种延迟加载服务的方法,以便它们仅在您需要时才加载。
使用 Composer,您的所有依赖项都将得到管理,自动加载器将神奇地创建出来。您只需要在代码的顶部放置一个 require_once __DIR__ . '/vendor/autoload.php';'
,从那时起,每当您第一次执行 new PhpMailer
时,它都需要 PHPMailer class文件。请参阅 how to install PHPMailer using Composer 的 PHPMailer 文档。
与在任何调用 PHPMailer 之前仅键入 require_once 相比,这看起来工作量很大,但在长 运行,当你的项目做大了,你就会盈利!
我还鼓励您阅读上面 link 中有关依赖注入的内容,因为这可能会帮助您更好地解耦和构建代码。一个好的入门容器可能是 PHP-DI。祝你好运!
可以的
require_once();
将只包含文件一次。其余时间调用它只会 return true(文件是否存在无关紧要)。
The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.