fork(1) download
  1. <?php
  2.  
  3. class my_class
  4. {
  5. public $var1;
  6.  
  7. public $var2;
  8.  
  9. public $var3;
  10.  
  11. private $data;
  12.  
  13. public function __construct()
  14. {
  15. $this->data = new stdClass;
  16. $this->data->var1 = 'a';
  17. $this->data->var2 = 'b';
  18. $this->data->var3 = 'c';
  19. $this->assignReferences();
  20. }
  21.  
  22. public function makeClone()
  23. {
  24. unset($this->var1); // turns $this->data->var1 into non-reference
  25. unset($this->var2); // turns $this->data->var2 into non-reference
  26. unset($this->var3); // turns $this->data->var3 into non-reference
  27.  
  28. $clone = clone $this; // this code is the same
  29. $clone->data = clone $clone->data; // as what would go into
  30. $clone->assignReferences(); // __clone() normally
  31.  
  32. $this->assignReferences(); // undo the unset()s
  33. return $clone;
  34. }
  35.  
  36. private function assignReferences()
  37. {
  38. $this->var1 = &$this->data->var1;
  39. $this->var2 = &$this->data->var2;
  40. $this->var3 = &$this->data->var3;
  41. }
  42. }
  43.  
  44. $original = new my_class;
  45. $new = $original->makeClone();
  46. $new->var3 = 'd';
  47.  
  48. echo $original->var3; // Output Should Be "c"
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
c