Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP How to check if a subclass has overridden a method of a superclass?

Tags:

php

reflection

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
}
like image 587
Andrew Avatar asked May 13 '13 13:05

Andrew


People also ask

How do we identify if a method is an overridden method?

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.

Does subclass override superclass?

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.

How do I access overridden methods?

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).

Can Super method be overridden?

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.


1 Answers

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.

like image 170
nice ass Avatar answered Oct 10 '22 02:10

nice ass