-1

Is possible clone php object class and alway change all available

Example

Class A{
  private $data;
  public function set($name, $value){
    $this->data[$name] = $value;
  }

  public function get($name){
    return isset($this->data[$name]) ? $this->data[$name] : null;
  }

  public function __clone(){
    $this->data = unserialize(serialize($this->data));
  }
}

Working with clone

$a = new A();
$a->set('dog', 'Kiki');

$b = clone $a;

var_dump($b->get('dog'));

dump value is 'Kiki';

So i need object for $b alway change dynamic when object $a is change example

$a = new A();
$b = clone $a;

$a->set('dog','Kiki');
var_dump($b->get('dog'));

dump value is null;

how to change dynamic object $b when object $a change ?

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
Peter Jack
  • 847
  • 5
  • 14
  • 29
  • 1
    If you want `$b` to change when `$a` changes, then why are you cloning? Just do `$b = $a`. – bishop Nov 02 '17 at 23:28
  • whats the point? –  Nov 02 '17 at 23:29
  • You could make `$b` reference `$a`... then it wont be a copy – Ice76 Nov 02 '17 at 23:32
  • Because i have some private class , and i need clone it to static object to be call anywhere in my project and work as sandbox ! – Peter Jack Nov 02 '17 at 23:35
  • So B should take over all changes made in A, but B shouldn't influence A, correct? – lunjius Nov 02 '17 at 23:47
  • By _definition_ `clone` creates a _copy_. Full stop. If you want `$b` to track changes to `$a`, then you need assignment. – bishop Nov 03 '17 at 00:00
  • @Jaspa Yes correct ! 100% correct , need get all change from A, and B work like sandbox , B shouldn't influence A – Peter Jack Nov 03 '17 at 00:20
  • Possible duplicate of [PHP Object Assignment vs Cloning](https://stackoverflow.com/questions/16893949/php-object-assignment-vs-cloning) – yivi Nov 03 '17 at 07:21

1 Answers1

-1

The only way to do this is to handle that on your own. I'd suggest to extend class A a little bit:

Class A{

  private $data;
  public $sandbox;

  public function set($name, $value){
    $this->data[$name] = $value;
    $this->applyChanges();
  }

  public function get($name){
    return isset($this->data[$name]) ? $this->data[$name] : null;
  }

  public function __clone(){
    $this->data = unserialize(serialize($this->data));
  }

  public function createSandBox() {
      $this->sandbox = new A();
      $this->sandbox = clone $this;
  }

  public function applyChanges() {
      $this->sandbox = clone $this;
  }

}
lunjius
  • 418
  • 3
  • 12