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
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
My solution will be based on the solution from this question How do you copy a PHP object into a different object type
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 );