tags:

views:

27

answers:

2

I have

class P {
    function fun() {
        echo "P"; 
    }
}

class Ch {    
    function fun() {
        echo "Ch";
    }
}

$x = new Ch();

How to call parent function fun from $x? Is it possible to do it directly or I have to write:

function callParent {
    parent::fun();
}
+1  A: 

Simple... don't have a method of the same name in the child, in which case the parent method will be inherited by the child, and a call to $x->fun() will call the inherited method.

Mark Baker
What if I want to have this method?
liysd
If you want to have that method, then you're making an explicit, educated choice to override the parent method. Therefore, you are subjecting yourself to needing to use an explicit call to parent::init(); if you wish to execute that code as well.
Mark Baker
+1  A: 

Assuming your code is actually meant to be this :

class P {
  function fun() {
    echo "P"; 
  }
}

class Ch extends P {
  function fun() {
    echo "Ch";
  }

  function callParent{
    parent::fun();
  }
}

$x = new Ch();

you indeed have to use parent::fun() to call P::fun.

This might be useful in case you're overriding a method which must be called in order for the parent class to properly be initialized, for example.

Like:

class Parent {
  function init($params) {
    // some mandatory code
  }
}

class Child extends Parent {
  function init($params) {
    parent::init();
    // some more code
  }
}
SirDarius