I have a parent class A, and child class B in PHP. Is there any way to clone instance of class A to instance of B, and to use B class properties later in B instance? Thanks
我有一个父类A和PHP中的子类B.有没有办法将类A的实例克隆到B的实例,并在B实例中稍后使用B类属性?谢谢
1 个解决方案
#1
14
My solution will be based on the solution from this question How do you copy a PHP object into a different object type
我的解决方案将基于此问题的解决方案如何将PHP对象复制到不同的对象类型
class childClass extends parentClass
{
private $a;
private $b;
function loadFromParentObj( $parentObj )
{
$objValues = get_object_vars($parentObj); // return array of object values
foreach($objValues AS $key=>$value)
{
$this->$key = $value;
}
}
}
$myParent = new parentClass();
$myChild = new childClass();
$myChild->loadFromParentObj( $myParent );
#1
14
My solution will be based on the solution from this question How do you copy a PHP object into a different object type
我的解决方案将基于此问题的解决方案如何将PHP对象复制到不同的对象类型
class childClass extends parentClass
{
private $a;
private $b;
function loadFromParentObj( $parentObj )
{
$objValues = get_object_vars($parentObj); // return array of object values
foreach($objValues AS $key=>$value)
{
$this->$key = $value;
}
}
}
$myParent = new parentClass();
$myChild = new childClass();
$myChild->loadFromParentObj( $myParent );