Php克隆无法正常工作

时间:2017-11-02 23:18:28

标签: php reference clone

可能是克隆php对象类,并且总是改变所有可用的

示例

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));
  }
}

使用克隆

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

$b = clone $a;

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

dump value is 'Kiki';

所以当对象$ a发生变化时,我需要$ b总是改变动态的对象 示例

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

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

dump value is null;

当对象$ a更改时如何更改动态对象$ b?

由于

1 个答案:

答案 0 :(得分:-1)

这样做的唯一方法就是自己处理。我建议稍微扩展A类:

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;
  }

}