0

Is there a way to override a function inside a class without touching the class coding?

We have the class, let's say it's located in foo.php:

class WPSEO_Frontend {
      public function head() {
            echo '<!-- / ', $this->head_product_name(), ". -->\n\n";
            return;
      }
}

So without modifying this class above, is there a way to remove this echo from the outside of the class, like (I know the below example isn't going to work):

bar.php

class WPSEO_Frontend overrides head {
      echo '';
      return;
}
Mitch
  • 73
  • 1
  • 10
  • Do you not have the ability to extend the class to override the public method, such as if you can't modify the calling code in any way to use a different class? – Michael Berkowski Feb 14 '17 at 00:17
  • @MichaelBerkowski Sorry I don't understand your question – Mitch Feb 14 '17 at 00:19
  • What I mean is, the normal way to handle this in PHP (and many other langs) is to create a class like `class WPSEO_Frontend_Subclass extends WPSEO_Frontend {}` and just redefine the method there. But if you do not have access to the code which calls `new WPSEO_Frontend()` to be able to substitute your subclass, that won't help. – Michael Berkowski Feb 14 '17 at 00:22
  • See also http://stackoverflow.com/questions/2931730/modify-a-method-function-at-runtime Unfortunately, PHP isn't like Ruby where this is doable and not even uncommon. – Michael Berkowski Feb 14 '17 at 00:22

1 Answers1

2

PHP doesn't support run-time function swizzling like the Swift language, for instance.

What you should try to do is instead create a "WPSEO_Frontend_Base" class and then create another "WP_SEO_Frontend" child class which extends from it overrides the head() function.

Here's some sample code:

wpseo.frontend.base.php

class WPSEO_Frontend_Base {
      public function head() {
            echo '<!-- / ', $this->head_product_name(), ". -->\n\n";
            return;
      }
}

wpseo.frontend.php

require 'wpseo.frontend.base.php';

class WPSEO_Frontend extends WPSEO_Frontend_Base {
  function head(){
    // Override head() here
  }
}
ablopez
  • 850
  • 4
  • 7
  • 3
    *"function swizzling"* is the newfangled way of saying [*monkey patch*](https://en.wikipedia.org/wiki/Monkey_patch) ? – Mulan Feb 14 '17 at 00:24