无法从类中加载swiftmailer。 我收到错误:找不到类“Swift_SmtpTransport”

I am implementing a mailing solution where if I call swiftmailer from the main index.php file like :

require_once '../swiftmailer/lib/swift_required.php';
...
$result = $mailer->send($message);

All is great. But when I use the same swiftmailer library in my application class to implement layout/design partition like this:

// File: controller.php

class Index {
      ...
      public function ignition() {
            ...
            spl_autoload_register(array($this, 'myClassLoaderFx'));
      }

      public function myClassLoaderFx($name) {
            $classes = array(
                  'Blah' => '../blah/Blah.php',
                  ...
                  'Swift' => '../swiftmailer/lib/swift_required.php'
            );
            if(!array_key_exists($name, $classes)){
                  die('Class not found');
            }
            require_once $classes[$name];
      }

// File: Mailer.php

class Mailer {
      ...
      public function main($recepient[], $sender, $subject, $body) {
            ...
            $transport = Swift_SmtpTransport::newInstance('xyz.google.com', 465, "ssl")->setUsername($this->username)->setPassword($this->password);
            ...
            $result = $mailer->send($message);
}

Upon execution I get : Class "Swift_SmtpTransport" not found. The library is loaded because I get all Swift class list in the netbeans context help. But, upon execution I get the error. I have done all possible spell checkings. Getting nowhere from here on. Please help.

php
douhuai2861
douhuai2861 我检查过拼写错误并检查了函数名称。没到达任何地方。谢谢。
大约 4 年之前 回复
douyi1855
douyi1855 答案就在这里:stackoverflow.com/questions/29626658/...使用“Swift_SmtpTransport::newyInstance()”如果你是一个拼写错误,或者如果你需要那个y来使它工作,那我就不是了。
大约 4 年之前 回复

1个回答

Looks like your swiftmailer class Swift() is loaded but its incomplete. You can take one of the following approaces to solve this :

  1. Add "extends Swift" to your class declaration in file Mailer.php.

    class Mailer extends Swift {

Or,

  1. Load the swiftmailer library in a construct() function of Mailer class.

    Remove the following line from myClassLoaderFx() function from controller.php : 'Swift' => '../swiftmailer/lib/swift_required.php'

    And Create a construct for Mailer() class in file Mailer.php public function __construct(){ require_once '../swiftmailer/lib/swift_required.php'; }

Go with the first approach of using spl_autoload_ function unless you want to keep swiftmailer away from the main application into a managed class. This can come in handy in case you would like to switch to another mailer. You wont have to make changes to controller.php etc.

douping1825
douping1825 谢谢! 有效。
大约 4 年之前 回复
立即提问