Problem with using preg_replace_callback
i have a problem when i use preg_replace_callback. i have google translator class and i want to translate all matches using开发者_C百科 it .
the code was .
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',create_function(
'$matches',
'return $translator->translate($matches);'),
$code);
when i make var dump for the var $code, i found its string"1" !!!
im sure that im using a right way for the class.
Thanks.
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
.
In PHP 5.3 you could use a Closure.
<?php
$code = preg_replace_callback(
'/_e\(\'(.*?)\'\)/',
function($matches) use ($translator) {
return $translator->translate($matches);
},
$code
);
Try to also pass the $translator as argument.
This could look like:
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',create_function(
'$translator,$matches',
'return $translator->translate($matches);'),
$code);
UPDATE: This code example does not work. The replace callback is invoked with only one argument while the anonymous function here expects 2 arguments. The working implementation would be:
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',create_function(
'$matches',
'global $translator; return $translator->translate($matches);'),
$code);
精彩评论