【问题标题】:Use parsedown classes static使用解析类静态
【发布时间】:2022-08-04 16:53:02
【问题描述】:

在我的代码中,我使用所有静态类,例如:Parsedown::text(\'text\');,如果我尝试像这样使用它,它会给我一条错误消息“不在对象上下文中使用 $this”,但我无法弄清楚如何像这样使用 Parsedown 因为我只能像这样实例化它:

$Parsedown = new Parsedown();
echo $Parsedown->text(\'text\');

函数文本代码

    function text($text)
    {
        # make sure no definitions are set
        $this->DefinitionData = array();

        # standardize line breaks
        $text = str_replace(array(\"\\r\\n\", \"\\r\"), \"\\n\", $text);

        # remove surrounding line breaks
        $text = trim($text, \"\\n\");

        # split text into lines
        $lines = explode(\"\\n\", $text);

        # iterate through lines to identify blocks
        $markup = $this->lines($lines);

        # trim line breaks
        $markup = trim($markup, \"\\n\");

        return $markup;
    }

如何使用 parsedown static ?

  • 为什么当它显然不是为此而设计的时,你想使用它静态吗?
  • 由于我使用我所有的静态类,它保持我的代码顺序

标签: php parsedown


【解决方案1】:

嗨,如果你想使用静态方法,你应该告诉 php 你的方法是静态的,例如在方法定义中,你可以像这样定义你的方法:

public static function text($text)
{
    # make sure no definitions are set
    self::DefinitionData = array();

    # standardize line breaks
    $text = str_replace(array("\r\n", "\r"), "\n", $text);

    # remove surrounding line breaks
    $text = trim($text, "\n");

    # split text into lines
    $lines = explode("\n", $text);

    # iterate through lines to identify blocks
    $markup = self::lines($lines);

    # trim line breaks
    $markup = trim($markup, "\n");

    return $markup;
}

如您所见,我使用Self:: 而不是$this-> 因为在静态函数中,您无法访问初始化数据,您也需要将公共变量定义为静态

那么你可以像这样使用你的功能

Parsedown::text('text');

【讨论】:

  • 它不起作用,但它帮助了我
【解决方案2】:

您可以将 Parsedown 类静态与 instance() 函数一起使用

echo Parsedown::instance()->text('Text'); 

实例功能码:

    static function instance($name = 'default')
    {
        if (isset(self::$instances[$name]))
        {
            return self::$instances[$name];
        }

        $instance = new static();

        self::$instances[$name] = $instance;

        return $instance;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多