How can the use of anonymous functions in preg_replace_callback impact variable scope in PHP?

When using anonymous functions in preg_replace_callback in PHP, the variable scope can be impacted because the anonymous function does not inherit variables from the parent scope by default. To solve this issue, you can use the "use" keyword to import variables from the parent scope into the anonymous function.

$var = 'Hello';
$string = 'Hello, world!';

$result = preg_replace_callback('/Hello/', function($matches) use ($var) {
    return $var;
}, $string);

echo $result; // Output: Hello, world!