将preg_replace_callback与外部类一起使用

时间:2011-10-25 19:16:33

标签: php oop preg-replace-callback

我有一个问题给你!

通常,如果在OOP上下文中调用回调函数,则必须使用array(&$this, 'callback_function')

这就是我想到的。

但是现在我想在外部类中调用一个回调,因为有很多callback_functions。出于结构原因,我想给他们一个自己的课。

我想:“好吧,制作一个这个类的实例并传递它而不是$ this。”

所以我尝试使用array($cb, 'callback_function')array($this->cb, 'callback_function'),但它不起作用。

我做错了什么?

感谢您的帮助!


编辑:

在我的基础班上,我有:

    function __construct()
    {
        // some other vars here

        $this->cb = new Callback();
    }

用以下方式调用它:

$newline = preg_replace_callback("/(^#+) (.*)/", array(&$this->cb, 'callback_heading'), $newline);

在我的回调课程中,我有:

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 = strlen($parameter[1]);
        $hashs++;
        if($hashs > 6)
            $hashs = 6;

        return "<h".$hashs."><span class=\'indented\'>".$parameter[1]."</span><strong>".$parameter[2]."</strong></h".$hashs.">";
    }

2 个答案:

答案 0 :(得分:7)

首先评论:

  

通常,如果在OOP上下文中调用回调函数,则必须使用array(&$this, 'callback_function')

不,通常(这些天)它是array($this, 'callback_function') - 没有&

然后,您可以放置​​代表对象的任何变量而不是$this

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

class That
{
   function method() {...}
}

$obj = new That;
$callback = array($obj, 'method');

这只是有效,请参阅callback pseudo type in the PHP Manual

的文档

更类似于您问题的代码片段:

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("<h%d><span class=\'indented\'>%s</span><strong>%s</strong></h%d>", $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);

答案 1 :(得分:1)

说你的外部课看起来像这样

<?php
class ExternalClass {
    function callback() {
        // do something here
    }
}

如果您的回调函数没有引用$ this,您可以静态调用它:

preg_replace_callback($pattern, 'ExternalClass::callback', $subject);

否则,您的方法在理论上工作。

preg_replace_callback($pattern, array(new ExternalClass, 'callback'), $subject);

Read more about callbacks