如何在php中将对象克隆到子类 [英] how to clone object to child class in php

查看:112
本文介绍了如何在php中将对象克隆到子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类A和PHP中的子类B.
有没有办法将类A的实例克隆到B的实例,以及稍后在B实例中使用B类属性?
谢谢

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

推荐答案

我的解决方案将基于此问题的解决方案How你复制一个PHP对象转换为不同的对象类型

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

这篇关于如何在php中将对象克隆到子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆