[Phpwm] Passing parameters to callback functions

Elliot Smith elliot at townx.org
Mon May 19 10:54:46 BST 2008


Hello Mike,

Mike Tipping wrote:
> I'm using preg_replace_callback() to replace content in a CMS system but
> need to pass some extra parameters to the call back function in addition to
> the matches array that is passed by default:
>
> $fileContent = preg_replace_callback('/{cms id="([\d]*)"}/'
> ,array($this,'replaceContent'), $fileContent);
>
> So replaceContent is defined as
>
> Function replaceContent($matches, $year, $month)
>
> Does anyone know if I can pass the $year, $month and how to do it. I know I
> can assign it to a class or session variable but this seems messy.
>
>   
Looking at the docs, you can use any callback type 
(http://us2.php.net/manual/en/language.pseudo-types.php#language.types.callback) 
as an argument to the function call. Apparently, this includes object 
methods or static class methods. So you could load up an object with 
your year and month, then pass it as the callback into the function. 
Maybe like this:

class YearMonthReplacer {
  function YearMonthReplacer($year, $month) {
    ... set instance variables here ...
  }

  function replaceContent($matches) {
    ... do stuff here with $matches, referencing $this->year and 
$this->month ...
  }
}

Call it like this:

$obj = new YearMonthReplacer(1970, 1);

$fileContent = "blah";

$fileContent = preg_replace_callback('/{cms id="([\d]*)"}/', 
array($obj,'replaceContent'), $fileContent);I haven't tested this, and 
syntax may be wrong (I've been doing too much Java recently), but 
something like that should work.


Hope that helps.
Elliot


>
> _______________________________________________
> Phpwm mailing list
> Phpwm at mailman.lug.org.uk
> https://mailman.lug.org.uk/mailman/listinfo/phpwm
>   


-- 
Elliot Smith
http://townx.org/




More information about the Phpwm mailing list