Search code examples
phpnamespacesphpmailer

use phpmailer nameclass in php class


I would like to use phpmailer at a php class, where should I place the default phpmailer namespace lines at the class?

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

my class:


require('./phpmailer/vendor/autoload.php');

class Email {

public function sent(){

}
}

Thank you!


Solution

  • Usually before anything else in the file, like this:

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    require './phpmailer/vendor/autoload.php';
    
    class Email {
    
        public function sent(){
    
        }
    }
    

    While I'm here, this is suspicious:

    require('./phpmailer/vendor/autoload.php');
    

    That looks like you're loading PHPMailer's own autoloader, which you shouldn't be going anywhere near. A typical project structure (e.g. all the examples provided with PHPMailer) would be something like:

    /project
      /public
        index.php
      /app
        (app files go here)
      /vendor
        autoload.php
        /composer
        /phpmailer
    

    Note that the autoloader is not in PHPMailer's own folder. In this kind of structure, the path to the autoloader from scripts in public or app folders will be:

    require '../vendor/autoload.php';
    

    It may be that I'm being thrown off here because you have called your own project phpmailer, but I thought I'd flag it as it looks strange.