【发布时间】:2017-07-13 16:14:21
【问题描述】:
我在第 3 方库中有以下类,我不应该修改它。
<?php
class MyMailer {
public function send() {
$mail = new PHPMailer();
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('myfriend@example.net', 'My Friend');
$mail->Subject = 'First PHPMailer Message';
$mail->Body = 'Hi! This is my first e-mail sent through PHPMailer.';
$mail->Send();
}
public function check(){
//code
}
}
如何覆盖或挂钩 send() 方法,或者如何使用我自己的新类覆盖整个类 MyMailer?
以下链接建议使用默认未与 PHP 捆绑的 runKit。所以不能保证它在我所有的服务器上都可用。我了解到这种方法称为 Monkey Patching。
所有答案都很老了,我希望有任何新的解决方案可用。
【问题讨论】:
-
你能不能扩展类并在不调用
parent::send()的新子类中添加send方法?如果您的代码需要实例化基础MyMailer则它将不起作用... -
@CD001:很多外部库都使用这种方法,我无法编辑它们以使用扩展类。
-
不,扩展课程将由您随心所欲
-
我明白了。但是我希望所有 3rd 方库类都使用我的扩展类?我无法控制那些外部库。更改这些库是不可能的,因为它会在更新期间产生问题。
标签: php class monkeypatching