Extending functionality by overwriting functions

I have a simple script based on a single class. I want to add several features to it, but only as an “opt-in” version - a plugin.

Class thing = {
  public function __construct() {
    // ... 
  }

  public function stuff() {
    // ...
  }
}

/* in thing_extension.php: */

Class thing_extension extends thing {
  public function stuff() {
    // everything in here runs instead of the original stuff()
    // this function is basically the same as stuff() but has the extra features
  // they're not just tagged on, they overwrite a lot of the original code
  }
}

It feels a little dirty because if you add thing_extension, the original stuff() becomes obsolete and there’s a large chunk of useless code lying about.

Am I on the right track here or is there a better (but still simple) way of doing this?

If you always plan on overriding a particular method, you could create an abstract class.


abstract class PluginBase
{
    abstract public function execute();
}

class ScrambledEggsPlugin extends PluginBase
{
    public function execute(){
        return 'I like Scrambled Eggs!!';
    }
}

Thanks Anthony. I read the manual page on this and I don’t think it will help, because it says I can’t create an instance of an abstract class. In my example, the user has to be able to use the “thing” class with or without the extension.

Then it sounds like you’re on the right track, after all, it’s one of the key components of OOP. As for the ‘wasted code’, it’s not wasted, it’s just not used in this particular configuration and affords you the flexibility you require.

Thanks, that’s very encouraging. :slight_smile: