重写 PHPMailer 发送方法
Overriding PHPMailer send method
我有一个扩展 PHPMailer 的自定义 class,我想重写发送函数。这似乎有效,但如果 parent::send()
正在处理活动对象或只是随机发送任何内容,我就无法解决问题。基本上 parent::send()
是如何知道我们正在作用于哪个特定对象的?
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;
}
}
}
我这样实例化:
$mail = new Mailer();
// create mailer stuff here
$mail->send(); // <- How do I know this is acting on the $mail instance?
正如 Ryan 所说,它无论如何都会起作用,但您可以轻松地对其进行测试。 send函数中不需要重复检查,只需要传回父函数returns的内容即可。调用父构造函数也是一个好主意,这样您在覆盖它时就不会错过它的作用,并且您应该始终确保覆盖的方法签名匹配。另外,避免在 465 上使用 SSL;它自 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();
}
}
我有一个扩展 PHPMailer 的自定义 class,我想重写发送函数。这似乎有效,但如果 parent::send()
正在处理活动对象或只是随机发送任何内容,我就无法解决问题。基本上 parent::send()
是如何知道我们正在作用于哪个特定对象的?
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;
}
}
}
我这样实例化:
$mail = new Mailer();
// create mailer stuff here
$mail->send(); // <- How do I know this is acting on the $mail instance?
正如 Ryan 所说,它无论如何都会起作用,但您可以轻松地对其进行测试。 send函数中不需要重复检查,只需要传回父函数returns的内容即可。调用父构造函数也是一个好主意,这样您在覆盖它时就不会错过它的作用,并且您应该始终确保覆盖的方法签名匹配。另外,避免在 465 上使用 SSL;它自 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();
}
}