Hi,

I have run into a problems when passing and object during a preg_replace_callback(). Normally with the preg_replace_callback() function, the callback value is a string containing the name of a function:

ex: preg_replace_callback('/match/', 'callbackFunctionName' $string)

trying to pass on object-bound function as the string won't work:

ex: preg_replace_callback('/match/', '$this->callbackFunctionName' $string)

however, you can get around this by passing an array($object,'callbackFunctionName') instead of a string:

ex: preg_replace_callback('/match/', array($object, 'callbackFunctionName'), $string)

There is still one problem with this however, and that is that manipulations performed on $object inside the object function don't seem to stick once the preg_replace_callback() function has ended. I have created the following class as an example. For some reason, changes to the $this->testCount variable are not preserved. This can be worked around by using the preg_replace() function in conjunction with the 'e' switch, but I would like to know why this other method is not working, since it is the proper function to be using here. Can anyone spot what the problem is here?

~Kevin

Example Class:

<?php

$template = new Template();
$page = $template->parse("my data string [test] ... [test] ... ");
echo $page;

class Template
{
var $testCount;

function Template () {}

function parse ($str)
{
// initialize the count
$this->testCount = 0;

// preg_replace using the 'e' switch: this will work
//$str = preg_replace('/(\[test\])/es', '$this->numbering();', $str);

// preg_replace_callback with object callback: won't work
$str = preg_replace_callback('/(\[test\])/s', array($this, 'numbering'), $str);

// print the current testCount: : Why doesn't $this reflect the changes???
echo "<b>\$testCount = $this->testCount</b><br>";

// return
return $str;

}

function numbering ( $matches=array() )
{
$this->testCount += 1;
return "{test}";
}

} // end class

?>

    Write a Reply...