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
}
getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.
Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With