The problem here is scope. Something similar to this would work in JavaScript, but JS and PHP handle scope differently. To access $translator
from within the anonymous function's scope, you need to declare it as a global.
<?php
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',
create_function('$matches',
'global $translator;'.
'return $translator->translate($matches);'),
$code);
?>
If you want to keep the anon as a one-liner, you can use the globals array:
<?php
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',
create_function('$matches',
"return $GLOBALS['translator']->translate($matches);"),
$code);
?>
If you have PHP 5.3.0 or later, this can be alleviated with closures and use
:
<?php
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',
function($matches) use ($translator) {
return $translator->translate($matches);
}, $code);
?>
This is assuming that $translator
was created in the same scope as $code
.