Cast the current object ($this) to a descendent class

后端 未结 5 687
刺人心
刺人心 2020-11-29 11:08

I have a class where it may be necessary to change the object to a descendent class further down the line. Is this possible? I know that one option is to return a copy of it

5条回答
  •  隐瞒了意图╮
    2020-11-29 11:45

    This is not possible because while an instance of a child class is also an instance of a parent class, the reverse is not true.

    What you could do is create a new instance of the child class and copy the values from the old object onto it. You can then return the new object which will be of type myChildClass.

提交回复
热议问题