PHP深度克隆对象 [英] PHP deep clone object
问题描述
场景:从数据库中获取电子邮件模板,并遍历收件人列表,为每个收件人个性化电子邮件.
The scenario: fetch an email template from the database, and loop through a list of recipients, personalising the email for each.
我的电子邮件模板作为嵌套对象返回.它可能看起来像这样:
My email template is returned as a nested object. It might look a little like this:
object(stdClass) {
["title"] => "Event Notification"
["sender"] => "notifications@mysite.com"
["content"] => object(stdClass) {
["salutation"] => "Dear %%firstname%%,"
["body"] => "Lorem ipsum %%recipient_email%% etc etc..."
}
}
然后我遍历收件人,将此$ email对象传递给personalise()函数:
Then I loop through the recipients, passing this $email object to a personalise() function:
foreach( $recipients as $recipient ){
$email_body = personalise( $email, $recipient );
//send_email();
}
当然,问题是我需要通过引用传递$ email对象,以便替换个性化标签-但是,如果这样做,原始对象将被更改,不再包含个性化标签.
The issue, of course, is that I need to pass the $email object by reference in order for it to replace the personalisation tags - but if I do that, the original object is changed and no longer contains the personalisation tags.
据我了解,克隆在这里无济于事,因为它只会创建一个浅表副本:电子邮件对象内部的内容对象不会被克隆.
As I understand, clone won't help me here, because it'll only create a shallow copy: the content object inside the email object won't be cloned.
我已经读过关于用unserialize(serialize($ obj))解决这个问题的知识-但是我读到的所有内容都说这对性能有很大的影响.
I've read about getting round this with unserialize(serialize($obj)) - but everything I've read says this is a big performance hit.
所以,两个人终于回答了我两个问题:
So, two finally get to my two questions:
- 在这里unserialize(serialize($ obj))是一个合理的解决方案吗?
- 还是我要把这件事弄错了?我有另一种方式吗 可以生成该电子邮件对象的个性化副本?
- Is unserialize(serialize($obj)) a reasonable solution here?
- Or am I going about this whole thing wrong? Is there a different way that I can generate personalised copies of that email object?
推荐答案
您可以添加 __clone()
方法发送到您的电子邮件类别.通过clone()克隆此类的实例时,将自动调用该方法.然后,您可以使用这种方法手动添加模板.
You could add a __clone()
method to your email class. Which is automatically called when an instance of this class is cloned via clone(). In this method you can then manually add the template.
示例:
class email {
__clone() {
$this->template = new template();
}
}
.
unserialize(serialize($object)); // would be another solution...
这篇关于PHP深度克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!