kylex kylex - 3 months ago 14
PHP Question

Overriding PHPMailer send method

I have a custom class which extends PHPMailer, and I want to override the send function. This appears to be working, but I'm having trouble wrapping my head around if

parent::send()
is working on the active object or just randomly sending whatever. Basically how does
parent::send()
know what specific object we're acting on?

class Mailer extends PHPMailer
{

public function __construct()
{
$this->isSMTP();
$this->Host = 'smtp.gmail.com';
$this->SMTPAuth = true;
$this->Username = '';
$this->Password = '';
$this->SMTPSecure = 'ssl';
$this->Port = 465;
}

/**
* Overrides parent send()
*
* @return boolean
*/
public function send() {
if (!parent::send()) {
// do some stuff here
return false;
} else {
return true;
}
}
}


I instantiate like so:

$mail = new Mailer();
// create mailer stuff here

$mail->send(); // <- How do I know this is acting on the $mail instance?

Answer

As Ryan said, it will be working anyway, but you can easily test it. You don't need to repeat the check in the send function, just pass back what the parent function returns. It's also a good idea to call the parent constructor so you don't miss out on what it does when you override it, and you should always ensure that overridden method signatures match. Also, avoid SSL on 465; it's been obsolete since 1998:

class Mailer extends PHPMailer
{

    public function __construct($exceptions = null)
    {
        parent::__construct($exceptions);
        $this->isSMTP();                      
        $this->Host = 'smtp.gmail.com';       
        $this->SMTPAuth = true;               
        $this->Username = '';                 
        $this->Password = '';                 
        $this->SMTPSecure = 'tls';             
        $this->Port = 587;
    }

    /**
     * Overrides parent send()
     *
     * @return boolean
     */
     public function send() {
        echo 'Hello from my subclass';
        return parent::send();
     }
}