Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a static method as the callback parameter in preg_replace_callback()?

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?

like image 760
Lee Avatar asked Jul 04 '11 18:07

Lee


1 Answers

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.

like image 60
tjm Avatar answered Oct 18 '22 13:10

tjm