Reputation: 83
Using PHP, how can a class determine if a subclass has overridden one if its methods?
Given the following two classes:
class Superclass {
protected function doFoo($data) {
// empty
}
protected function doBar($data) {
// empty
}
}
class Subclass extends Superclass {
protected function doFoo($data) {
// do something
}
}
How can a method be added to Superclass that will perform different actions depending on which of its methods have been overridden?
For example:
if ([doFoo is overridden]) {
// Perform an action without calling doFoo
}
if ([doBar is overridden]) {
// Perform an action without calling doBar
}
Upvotes: 5
Views: 1007
Reputation: 16709
With ReflectionMethod::getPrototype
.
$foo = new \ReflectionMethod('Subclass', 'doFoo');
$declaringClass = $foo->getDeclaringClass()->getName();
$proto = $foo->getPrototype();
if($proto && $proto->getDeclaringClass()->getName() !== $declaringClass){
// overridden
}
If the classes match, it wasn't overridden, otherwise it was.
Or if you know both class names, simply compare $declaringClass
against the other class name.
Upvotes: 10