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
What you proposed actually works, except you had some incorrect code. The following version works:
class MyClass{
protected $n = 0;
public $array = array();
public function storeOldVersion(){
$this->array[] = clone $this;
$this->n = 2;
}
}
$a = new MyClass();
$a->storeOldVersion();
echo "<pre>";
var_dump( $a ); // retuns class with n = 2
var_dump( $a->array ); // return array with one class having n = 0
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.
$clone = clone $this;
$clone->array = array();
$this->array[] = $clone;
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.
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.
<?php
class MyClass{
private $n = 0;
private $array = array();
public function storeOldVersion(){
$clone = clone $this;
$clone->array = null;
$this->array[] = $clone;
}
}
$c = new MyClass();
$c->storeOldVersion();
var_dump($c);