gpt4 book ai didi

php - 将 preg_replace_callback 与外部类一起使用

转载 作者:行者123 更新时间:2023-12-02 07:09:04 27 4
gpt4 key购买 nike

我有一个问题要问你!

通常,如果您在 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.">";
}

最佳答案

先评论一下:

Normally, if you call a callback function within an OOP context you have to use 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);

关于php - 将 preg_replace_callback 与外部类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7894590/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com