本文介绍了将当前对象($ 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

推荐答案

如其他答案所述,您可以使用令人讨厌的 black magic 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)强制转换为后代类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:44