0

I'm trying to replace my deprecated code with preg_replace() and the /e modifier with preg_replace_callback().

But right now I run into an error which I don't know why I get it.

Old code:

function getItem( $item, $tmp ){
    return preg_replace('/\{([A-Za-z0-9_]+)}/e', '$item["$1"]', $tmp);
}

new code:

function getItem( $item, $tmp ) {
    return preg_replace_callback('/\{([A-Za-z0-9_]+)}/', function ($m){
        return $item[$m[1]];  //Line 129
    }, $tmp);
}

Error:

Notice: Undefined variable: item in /home/merttugoto/public_html/admin/inc/dynamic.cls.php on line 129

Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • You did almost everything correct. The only thing left is that `$item` is out of scope in your anonymous function. So you have to pass it either with `use()` or not recommended `global`. – Rizier123 May 11 '16 at 07:43
  • Thanks for your answer. But I'm new in php, I do my jobs in c# can you explain more please? – Görkem Yazıcı May 11 '16 at 08:04
  • Yes of course. So PHP has function scope for variables. See: http://stackoverflow.com/q/16959576 This means a variable defined outside of a function, won't be accessible in the function itself unless you pass that variable in some way to the function. See: https://3v4l.org/MJ71F So since you pass a callback to `preg_replace_callback()` you can't pass the variable `$item` as parameter, which you need in your code, to the callback. So you either need to use `use()` or `global`. So I would use `use()` like this: `function ($m)use($item){...` and make the `$item` accessible in the callback. – Rizier123 May 11 '16 at 08:08
  • You're welcome. Have a nice day :) – Rizier123 May 11 '16 at 08:15

0 Answers0