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

Using PHP, how can a class determine if a subclass is overridden 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 I add a method to a superclass that will perform different actions depending on which of its methods has been overridden?

For instance:

 if ([doFoo is overridden]) { // Perform an action without calling doFoo } if ([doBar is overridden]) { // Perform an action without calling doBar } 
+4
source share
1 answer

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 was not canceled, otherwise it was.


Or, if you know both class names, simply compare $declaringClass with another class name.

+9
source

Source: https://habr.com/ru/post/1480486/


All Articles