In response to another question I asked about regular expressions, I was told to use the preg_replace_callback
function (PHP regex templating - find all occurrences of {{var}}) as a solution to my problem. This works great, but now I have a question relating to variable scope in callback functions.
The function that parses the text is part of a class, but the data that I want to use is stored locally in the function. However, I have found that I cannot access this data from inside my callback function. Here are the ways that I have tried so far:
- Implement the callback as a private class function, passing
'$this->callback_function'
as the callback parameter (doesn't work, php has a fatal error) - Implement the callback inside the function that uses it (see example below) but this didn't work either because
$newData
is not in scope insidecallback_function
Any ideas as to how I can access $newData
inside my callback function, preferably without using globals?
Many thanks.
Example below for the second attempt (doesn't format properly when I put it after the bullet point)
public function parseText( $newData ) {
...
function callback_function( $matches ) {
... //something that uses $newData here
}
...
preg_replace_callback( '...', 'callback_function', $textToReplace );
}