开发者

How to convert a child instance to parent class and the reverse in PHP?

$child_instance = (childClas开发者_如何学JAVAs)$parent_instance;
$parent_instance = (parentClass)$child_instance;

Or is it possible?


Okay, I am pretty new to OOP in PHP too, and hence, had spent like an hour to look for a way to convert a child class instance to a parent class instance.

Alas, found it!

In your child class, just have this method:

function loadChildWithParent($instanceOfParent) {
        $props = get_object_vars($instanceOfParent);
        foreach ($props as $key => $val)
        {
            $this->$key = $val;
        }
}

And in your parent class, you can just call this method via:

$objNew = new student();
$objNew->voidLoadStudent($this);


No. After you use new ClassA you cannot change the type of class the class of that object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜