将当前对象 ($this) 转换为后代类 [英] Cast the current object ($this) to a descendent class

查看:19
本文介绍了将当前对象 ($this) 转换为后代类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,可能需要将对象更改为后续的后代类.这可能吗?我知道一种选择是返回它的副本,但使用子类代替,但实际修改当前对象会很好......所以:

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 but using the child class instead, but it'd be nice to actually modify the current object... so:

class myClass {
  protected $var;

  function myMethod()
  {
    // function which changes the class of this object
    recast(myChildClass); 
  }
}

class myChildClass extends myClass {
}

$obj = new myClass();
$obj->myMethod();
get_class_name($obj); // => myChildClass

推荐答案

如其他答案所述,您可以使用令人讨厌的黑魔法 PECL 扩展来实现.

You can, as described in other answers, do it with nasty black magic PECL extensions.

虽然,你真的不想要它.您想在 OOP 中解决的任何问题都有符合 OOP 的方法来解决.

Though, you seriously don't want it. Any problem you want to solve in OOP there's an OOP-compliant way to do it.

运行时类型层次结构修改不符合 OOP(实际上,这是有意识地避免的).有些设计模式应该适合您的需求.

Runtime type hierarchy modifications are not OOP-compliant (in fact, this is consciously avoided). There are design patterns that should fit what you want.

请告诉我们你为什么要那样做,我相信一定有更好的方法来做到这一点;)

Please, tell us why do you want that, I'm sure there must be better ways to do it ;)

这篇关于将当前对象 ($this) 转换为后代类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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