3

(How) Is it possible to use a variable within a callback-function? For example I'd like to use the variable $add within my callback-function:

private function addToWord($add) {
    return preg_replace_callback(
        '/([a-z])+/i',
        function($word, $add) {
            return $word.$add;
        },
        $this->text);
}
R_User
  • 9,932
  • 23
  • 73
  • 118

1 Answers1

6

You can use use keyword here:

private function addToWord($add) {
    return preg_replace_callback(
        '/([a-z])+/i',
        function($word) use ($add) {
            return $word[1] . $add;
        },
        $this->text);
}
Community
  • 1
  • 1
anubhava
  • 713,503
  • 59
  • 514
  • 593