How to use a static method as the callback parameter in preg_replace_callback()?
Solution 1
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 (dead link), for details of valid callbacks.http://php.net/manual/en/language.pseudo-types.php
N.B. Reading there, it seems since 5.2.3, you can use your method, as long as the callback function is static.
Solution 2
You can do it like this:
return preg_replace_callback($pattern, array("Utilities", "LinksCallback"), $input)
Reference: http://php.net/callback
Solution 3
You can also use T-Regx library:
pattern($pattern)->replace($input)->callback([Utilities::class, 'LinksCallback']);
Comments
-
Lee almost 2 years
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?
-
Nahydrin almost 13 yearsI don't know about static functions, so the above solution may be correct. But if it's a regular function then use this:
return preg_replace_callback( $pattern, array( &$this, "LinksCallback" ), $input );
-
Chris Laplante almost 13 yearsThat will definitely work for instances. For static functions, my notation is required. I guess they (Zend) assume that most references to static functions will be those inside static classes.
-
Lee almost 13 yearsYes, the LinksCallback() is static and in the class Utilities. I'll give it a try thanks.
-
Lee almost 13 yearsYes thanks. My code should be correct according to the method PHP.net uses, although their example is similar, they use a regular function - not a class static method. Edit: The problem was simply omitting the static keyword.
-
benmarks over 11 yearsMissed the NB, which was my issue. FYI - if using within a class instance,
array($this,'method_name')
does the trick.