1

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 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 );
}
Community
  • 1
  • 1
a_m0d
  • 12,034
  • 15
  • 57
  • 79

2 Answers2

2
  • 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 );
    }
    
}

?>
Community
  • 1
  • 1
Jordan S. Jones
  • 13,703
  • 5
  • 44
  • 49
-2

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.

Daniel Sorichetti
  • 1,921
  • 1
  • 20
  • 34