phpoopparsedown

Extend class in PHP


I am trying to extend a class:

class CustomParsedown extends Parsedown {
    protected function blockComment($Line) { return; }
    protected function blockCommentContinue($Line, array $Block) { return; }
    protected function blockHeader($Line) { return; }
    protected function blockSetextHeader($Line, array $Block = NULL) { return; }
}

function markdown($markdown) {
    return CustomParsedown::instance()->setMarkupEscaped(true)->text($markdown);
}

If I run markdown() with markdown from another page, the changes in the code do not go into effect. For example, I can still create a heading. Am I extending the class correctly?


Solution

  • It looks like Parsedowns static function instance() is referencing $instance = new self(); which means it will instantiate a new Parsedown class and not your extending class.

    Try duplicating their instance method into your class, I've also changed new self into new static.

    class CustomParsedown extends Parsedown {
      static function instance($name = 'default')
      {
          if (isset(self::$instances[$name]))
          {
              return self::$instances[$name];
          }
          $instance = new static();
          self::$instances[$name] = $instance;
          return $instance;
      }
      private static $instances = array();
    }
    

    https://github.com/erusev/parsedown/blob/master/Parsedown.php


    See also New self vs. new static