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:
'$this->callback_function'
as the callback parameter (doesn't work, php has a fatal error)$newData
is not in scope inside callback_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 );
}
- Implement the callback as a private class function, passing '$this->callback_function' as the callback parameter (doesn't work, php has a fatal error)
preg_replace_callback( '...', 'callback_function', $textToReplace );
Change your call to be preg_replace_callback ('...', array($this, 'callback_function'), $textToReplace);
while callback_function
is a private method in your class.
<?php
class PregMatchTest
{
private callback_function ($matches)
{
// ......
}
public function parseText ($newData)
{
// ....
preg_replace_callback( '...', array($this, 'callback_function'), $textToReplace );
}
}
?>
I don't think it's possible without using globals, maybe just set it on the $_GLOBALS array and then unset it if you wish.