如何创建一个 PHP 类,其中的函数之一可以克隆自身?
基本上,我需要将该对象的过去版本以其当前状态存储在数组中。比如:
public class MyClass{
$n = 0;
$array = array()
storeOldVersion(){
$this->array[] = clone $this;
}
}
我知道我做了类似“clone $this->n”的事情,但是我如何才能真正克隆 MyClass 对象本身,并将其存储到 MyClass 对象保存的数组中?
谢谢
Basically, I need to store past versions of this object in its current state in an array. Something like:
public class MyClass{
$n = 0;
$array = array()
storeOldVersion(){
$this->array[] = clone $this;
}
}
I know I do something like "clone $this->n", but how can I literally clone the MyClass object itself, and store it into an array the MyClass object holds?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您提出的建议实际上有效,只是您有一些不正确的代码。以下版本有效:
警告一句话
如果您多次调用 storeOldVersion() ,它会递归地克隆包含其他克隆的“数组”,并且您的对象可能会呈指数级增长。在将数组变量存储到数组中之前,您可能应该从克隆中取消设置数组变量
。
What you proposed actually works, except you had some incorrect code. The following version works:
A word of warning though
If you call storeOldVersion() more than once, as is, it will recursively clone the "array" that contains other clones and your object could get pretty massive exponentially. You should probably unset the array variable from the clone before storing it in the array..
e.g.
您还可以尝试对复杂对象进行序列化。它将把对象存储为字符串。毕竟,您可以将字符串反序列化为具有过去状态的对象。
http://php.net/manual/en/language.oop5.serialization.php
You can also try serialization for complicated objects. It will store the object as a string. After all you can unserialize string to object with the past state.
http://php.net/manual/en/language.oop5.serialization.php
经过一些清理,您的代码就可以工作了。但是,您可能希望清除存储的旧版本中旧版本的
$array
,否则您最终会遇到巨大的递归混乱。With a little cleanup, your code works. However, you probably want to clean out the
$array
of old versions in the old versions you store, otherwise you're going to end up with a huge recursive mess on your hands.