在PHP7中从父级创建子对象

时间:2016-10-20 15:09:54

标签: php

假设我有一个父类X和一个子类Y extends X。现在我有一个X的对象,它包含公共和私有属性。

现在,我想创建一个Y的对象,该对象的值与我之前创建的X完全相同。

NOT WORKING EXAMPLE

class X { public $var; }

class Y extends X {}

$x = new X();
$x->var = 5;

$y = new Y(); // This object should have the same properties as X    
echo $y->var; // Should echo 5

修改

我知道这不是PHP应该表现的标准方式,但是我需要这个功能来转换一些遗留的PHP代码以使用一组新的子类。

1 个答案:

答案 0 :(得分:2)

我现在无法想到自动执行此操作。

但是,您可以在Y类中包含一个构造函数,以接受X实例作为参数:

class Y extends X {
  public function __construct(X $x) {
    $this->var = $x->var;
    // if you want to keep the two bound to each other, you could do
    // $this->var =& $x->var;
  }
}

然后像:

一样使用它
$x = new X();
$x->var = 5;

$y = new Y($x); // pass original X instance
echo $y->var; // now is 5

还有可能clone一个对象,但这不能改变它的类。