2

我有一个问题问你!

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

这就是我想出来的。

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

我想:“好吧,创建一个此类的实例并传递它而不是 $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.">";
    }
4

2 回答 2

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

这很有效,请参阅PHP 手册中的回调伪类型文档。


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

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);
于 2011-10-25T19:23:36.230 回答
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);

阅读有关回调的更多信息

于 2011-10-25T19:23:18.007 回答