top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to call an overridden non static method in the parent class in PHP?

0 votes
655 views

Calling an overridden static method is easy, just go: parent::MethodName().

The point is that I want to have the same 'output' method name in both classes, so that whatever has one of them just calls $xxx->output() and it will work.

I want the method in the child class to use what the parent class has and just add a bit to it. I don't want to duplicate a lot of code in class B that is already in class A.

The way that I have a (hopefully temporary) workaround is to in class A have a method do_output() that is called by A::output() and B::output(). That works, but is clunky.

Is there a neat way of doing what I want ?

class A {
  private $v_a;

  // Does all sorts of things and returns a value
  function output() {
   return array('a' => $this->v_a);
  }
}

class B extends A {
  private $v_b;

  // Takes what output() in class A returns, adds some more and returns that
  function output() {
  $ret = parent::output();
   $ret['b'] = $this->v_b;
  return $ret;
  }
}

$var_a = new A;

$var_b = new B;

print_r($var_a->output());

// I want to see the value of v_a and v_b:
print_r($var_b->output());
posted Jun 4, 2014 by Meenal Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

You use the same construct. The code you posted works fine. Try putting in some values for those properties to make it more explicit, but here's the output:

 Array
 (
 [a] =>
 )
 Array
 (
 [a] =>
 [b] =>
 )
answer Jun 4, 2014 by Kaushik
Thanks now it works.
...