PHP upcasting object [duplicate]

a 夏天 提交于 2019-12-08 08:39:09

问题


can I upcast an object to it's parent object?

Example Code

class ClassA {
  public function foo(){
    echo get_class($this);
  }
}

class ClassB extends ClassA {
  public function foo(){
    echo get_class($this); // prints ClassB :)
    parent::foo();         // prints ClassB / I want ClassA :(
  }
}

$B = new ClassB();
$B->foo();

is it possible in PHP;

In my scenario I'm building ClassB and I want to overide function ClassB::Foo() to extend its behavior and then handle the control back to it's parent function ClassA::Foo() but the code breaks because it is now an object of ClassB. Plz don't blame me about "code smells" because I now that its ugly! ClassA is out of my control... :-)


回答1:


Try using the __CLASS__ Magic Constant. It returns the class name that you are currently in, regardless of any inheritance going on.



来源:https://stackoverflow.com/questions/24105260/php-upcasting-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!