Using preg_replace_callback with external class

前端 未结 2 1572
情书的邮戳
情书的邮戳 2021-01-15 16:15

I have a question for you!

Normally, if you call a callback function within an OOP context you have to use array(&$this, \'callback_function\')

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-15 16:50

    First a comment:

    Normally, if you call a callback function within an OOP context you have to use array(&$this, 'callback_function')

    No, normally (these days) it's array($this, 'callback_function') - without the &.

    Then, instead of $this you can put any variable that's representing an object:

    $obj = $this;
    $callback = array($obj, 'method');
    

    or

    class That
    {
       function method() {...}
    }
    
    $obj = new That;
    $callback = array($obj, 'method');
    

    This just works, see the documentation of the callback pseudo type in the PHP Manual.


    More similar to the code fragments of your question:

    class Callback
    {
        function __construct()
        {
            $this->list = array("num" => 0, "dot" => 0, "normal" => 0);
            $this->td = array("strike" => false, "bold" => false, "italic" => false, "underline" => false, "code" => false);
        }
    
        public function callback_heading($parameter)
        {
            $hashs = min(6, 1+strlen($parameter[1]));
    
            return sprintf("%s%s", $hashs, parameter[1], $parameter[2], $hashs);
        }
    }
    
    class Basic 
    {
        /** @var Callback */
        private $cb;
        function __construct()
        {
            // some other vars here
            $obj = new Callback();
            $this->cb = array($obj, 'callback_heading');
        }
        function replace($subject)
        {
            ...
            $result = preg_replace_callback($pattern, $this->cb, $subject);
        }
    }
    
    $basic = new Basic;
    $string = '123, test.';
    $replaced = $basic->replace($string);
    

提交回复
热议问题