【问题标题】:Extend class in PHP在 PHP 中扩展类
【发布时间】:2015-11-03 02:13:07
【问题描述】:

我正在尝试扩展一个类:

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);
}

如果我从另一个页面运行带有降价的markdown(),代码中的更改不会生效。例如,我仍然可以创建标题。我是否正确扩展了课程?

【问题讨论】:

  • 顺便问一下你的PHP是什么版本的?

标签: php oop parsedown


【解决方案1】:

看起来 Parsedowns static function instance() 正在引用 $instance = new self();,这意味着它将实例化一个新的 Parsedown 类,而不是您的扩展类。

尝试将他们的实例方法复制到您的类中,我还将new self 更改为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


另见New self vs. new static

【讨论】:

  • 修改代码后得到Cannot access property CustomParsedown::$instances
  • 好的,把private static $instances = array();也加入你的班级
  • 嗯,现在我在line 1384 上收到Undefined index: name 。没关系,这是我的代码中的一个错误。
  • 这很奇怪,因为现在我查看了他们的文档,您已经完全按照他们的文档进行了操作,但它不起作用...github.com/erusev/parsedown/wiki/Tutorial:-Create-Extensions
  • 没错。我也很困惑,特别是因为似乎没有与这个确切问题相关的任何 github 问题。
猜你喜欢
  • 1970-01-01
  • 2012-06-27
  • 2012-07-31
  • 2013-02-06
  • 2017-01-09
  • 2016-05-09
  • 1970-01-01
相关资源
最近更新 更多