且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 preg_replace_callback() 中使用静态方法作为回调参数?

更新时间:2023-02-18 17:08:36

在 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.