如何在 preg_replace_callback() 中使用静态方法作为回调参数? [英] How to use a static method as the callback parameter in preg_replace_callback()?

查看:32
本文介绍了如何在 preg_replace_callback() 中使用静态方法作为回调参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 preg_replace_callback 查找文本链接并将其替换为实时链接:

http://www.example.com

www.example.com</a>

我为函数提供的回调函数在另一个类中,所以当我尝试时:

return preg_replace_callback($pattern, "Utilities::LinksCallback", $input);

我收到一个错误,声称该函数不存在.有什么想法吗?

在 PHP 中,当使用类方法作为回调时,必须使用 array 形式的回调.也就是说,您创建一个数组,其第一个元素是类(如果方法是静态的)或类的实例(如果不是),第二个元素是要调用的函数.例如

class A {公共函数 cb_regular() {}公共静态函数 cb_static() {}}$inst = 新 A;preg_replace_callback(..., array($inst, 'cb_regular'), ...);preg_replace_callback(..., array('A', 'cb_static'), ...);

您正在调用的函数当然必须在您使用回调的范围内可见.

有关有效回调的详细信息,请参阅 http://php.net/manual/en/language.pseudo-types.php(死链接).

注意在那里阅读,似乎从 5.2.3 开始,您可以使用您的方法,只要回调函数是静态的.

I'm using preg_replace_callback to find and replace textual links with live links:

http://www.example.com

to

<a href='http://www.example.com'>www.example.com</a>

The callback function I'm providing the function with is within another class, so when I try:

return preg_replace_callback($pattern, "Utilities::LinksCallback", $input);

I get an error claiming the function doesn't exist. Any ideas?

In PHP when using a class method as a callback, you must use the array form of callback. That is, you create an array the first element of which is the class (if the method is static) or an instance of the class (if not), and the second element is the function to call. E.g.

class A {
     public function cb_regular() {}
     public static function cb_static() {}
}

$inst = new A;

preg_replace_callback(..., array($inst, 'cb_regular'), ...);

preg_replace_callback(..., array('A', 'cb_static'), ...);

The function you are calling of course has to been visible from within the scope where you are using the callback.

See http://php.net/manual/en/language.pseudo-types.php(dead link), for details of valid callbacks.

N.B. Reading there, it seems since 5.2.3, you can use your method, as long as the callback function is static.

这篇关于如何在 preg_replace_callback() 中使用静态方法作为回调参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆