quape quape - 4 years ago 122
PHP Question

call overwritten parent function from a child in php

How is it possible to call a overwritten parent function recursively from a child instance? Since I'm not using static methods I can't use

parent::method()
but have to do somehow different. I have a feeling that there is a better approach to my problem, maybe through a design pattern. This is my class structure:

class Creature {
public function eat() {
// feed and digest
}
}

class Mammal extends Creature {
public function eat() {
// gather and chew
}
}

class Human extends Mammal {
public function eat() {
// have a meal
}
}

class WesternPerson extends Human {
public function eat() {
// use knife & fork
}
}

$me = new WesternPerson();
$me->eat();


Calling
eat()
shall go recursively upwards from the special to the very abstract class. Most simple way would be if I could call the parent function with the same name from within the overwritten one. But I know, it's overwritten, so I can't.

Answer Source

The :: isn't just for static methods. It is the scope resolution operator. It is used any time you want to utilized a function that exists in scope other then your contextual scope.

parent, static, and self are language constructs that reference different scopes that relate to your calling scope.

So in this case

 parent::eat()

will call the Human::eat in the WesternPerson::eat context (ie $this will mean the WesternPerson Instance in the Human::eat context)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download