OOP-子类调用父类';方法,而不丢失其上下文


OOP - Child class call parent class' method without losing its context

我有一个从类a继承的类B。类a定义了一个方法,例如toArray(),该方法将循环遍历属性并返回一个带有属性的数组。

我想调用$b->toArray(),得到一个b而不是A的属性数组(尽管该方法是在A中定义的)。

类似这样的东西:

class A{
    public function toArray(){
        return get_object_vars($this); //$this WHAT is $this?! I want it to be different depending on the which class is instantiated.
    }
}
class B extends A{
    public $my_var = 'Some value';
}
$b = new B;
$b->toArray(); //should contain my_var

上面的代码失败。它将不返回任何内容,因为A没有属性。我如何用OOP实现这一点(更确切地说,在PHP中,但如果有一般的解释,那就太好了)。

方法本身是正确的,但问题是,在a类中没有函数toArray()

您必须将函数foo()重命名为toArray()

试试这个:

class A {
    public function toArray() {
        return get_object_vars( $this ); //$this WHAT is $this?! I want it to be different depending on the which class is instantiated.
    }
}
class B extends A {
    public $my_var = 'Some value';
}
$b = new B;
var_dump( $b->toArray() ); //should contain my_var

输出:

array(1) {
  ["my_var"]=>
  string(10) "Some value"
}