views:

580

answers:

2

Hi, In response to another question I asked about regular expressions, I was told to use the *preg_replace_callback* function (http://stackoverflow.com/questions/959017/) 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 );
}
A: 

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 S
+1  A: 
  • 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 );
    }

}

?>
Jordan S. Jones
Hey, thanks, that's just what I was after.
a_m0d