2

I'm trying to instantiate the PHP mailer class which i've installed using composer. The class is located in vendor\phpmailer\phpmailer\class.phpmailer.php

-Project
  -src
      -SmtpHandler.php
  -vendor
     -phpmailer
         -phpmailer
            class.phpmailer.php
  index.php

I'm trying to load this class inside SmtpHandler as follows:

<?php
namespace Fusion;

require_once __DIR__ . '/../vendor/autoload.php';
class SmtpHandler {

var $mail;

function __construct () {
    $this->mail = new PHPMailer;

my composer.json file is autoloading my php classes like so:

 "autoload": {
    "psr-4": {
         "Fusion\\": "src"
    }

},

when $this->mail = new PHPMailer; is called, i recieve an error Fatal error: Class 'Fusion\PHPMailer' not found in /var/www/proj/Project/src/SmtpHandler.php on line 8

Do i need to use vendor\phpmailer\phpmailer\class.phpmailer ? or am i using psr-4 wrong?

Thanks

Juakali92
  • 1,155
  • 8
  • 20
  • 1
    For future reference (when it's released!), PHPMailer 5.4 declares a namespace and uses a PSR-4 naming layout. – Synchro Dec 30 '15 at 20:25
  • You need to get in the habit of [accepting answers](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) which help you to solve your issues. You'll earn points and others will be encouraged to help you. – Jay Blanchard Apr 01 '16 at 21:04
  • This is over 3 months old, when i was fairly new to the site like i still am. There's no need to scout my profile to pick up on a mistake i made – Juakali92 Apr 01 '16 at 21:07
  • Scouting isn't necessary. It shows up on this page. You should accept the answer so others who come across this thread know it was correct and helpful. – prawg May 25 '16 at 20:37

1 Answers1

7

Add after the namespace(namespace Fusion;) add use PHPMailer as PHPMailer; or when instanciating do the following: new \PHPMailer;// instanciate from outside the current namespace

This is because php tries to instanciate Fusion\PHPMailer from your current namespace.

ka_lin
  • 9,329
  • 6
  • 35
  • 56
  • fantastic, I'm new to using composer so this is all new teritory. But your answer did the trick. – Juakali92 Dec 30 '15 at 18:07
  • Does this apply to any dependcies such as the facebook sdk also? Or do they differ depending on each one? – Juakali92 Dec 30 '15 at 21:05
  • If you declared your own namespace yes, you must add a backslash or define it wih `use` or instanciate the class with the namespace: `$fb = new Facebook\Facebook...`. This is beacause Facebook sdk has `Facebook` as namespace as I read earlyer here (https://developers.facebook.com/docs/php/Facebook/5.0.0) – ka_lin Dec 31 '15 at 13:14