I have a class Parent
which has a method calculateRevenue();
I also have a class Child
that extends Parent
. What I want to do is have the same method name in Child
class calculateRevenue();
which would call the method of the Parent
class method, and then execute the Child
method.
Is this possible? Or the same name will override the method functionality without the ability to call the Parent
method?
Yes this is possible.
class Ancestor
{
public function someMethod()
{
return 'foo';
}
}
class Child extends Ancestor
{
public function someMethod()
{
$results = parent::someMethod();
return $results . ' bar';
}
}
$c = new Child;
echo $c->someMethod() . "
";
Output: foo bar
It would be something like this:
class Parent {
public function calculateRevenue() {
return 1;
}
}
class Child extends Parent {
public function calculateRevenue() {
$parentRevenue = parent::calculateRevenue();
return 1 + $parentRevenue;
}
}
You must use the reserved word "parent" to call the class parent methods.
In this case the "Child" class uses the "extend" keyword to ihnerit "Parent" class methods. Now "Child" class can use all parent methods with the reserved keyword "parent".