2011-07-30 29 views
0

我使用preg_replace_callback時遇到問題。我有谷歌翻譯類 ,我想翻譯使用它的所有比賽。使用preg_replace_callback問題

代碼是。

$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',create_function(
'$matches', 
'return $translator->translate($matches);'), 
$code); 

當我爲var $代碼進行var轉儲時,發現它的字符串「1」!!!

即時通訊使用正確的方式爲類。

謝謝。

+0

需要看'translate()'方法。它只需要一個參數('$ matches'數組)並返回一個字符串。 – ridgerunner

+0

嘗試添加'全球$譯者;'線,只是試試... –

+0

谷歌翻譯今年將停業,你不應該依賴它。 –

回答

2

這裏的問題是範圍。類似這樣的東西可以在JavaScript中工作,但JS和PHP處理範圍的方式不同。要從匿名函數的範圍內訪問,您需要將其聲明爲全局函數。

<?php 
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/', 
      create_function('$matches', 
       'global $translator;'. 
       'return $translator->translate($matches);'), 
      $code); 
?> 

如果你想要保持匿名的一行代碼,您可以使用全局變量數組:

<?php 
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/', 
      create_function('$matches', 
       "return $GLOBALS['translator']->translate($matches);"), 
      $code); 
?> 

如果你有PHP 5.3.0或更高版本,這可以用封閉緩解和use

<?php 
$code = preg_replace_callback('/_e\(\'(.*?)\'\)/', 
      function($matches) use ($translator) { 
       return $translator->translate($matches); 
      }, $code); 
?> 

這是假設中相同的範圍創建爲$code

+0

可能最好的辦法是使靜態功能,以便他可以訪問'Translator :: tranaslate($ matches);',從而避免全局... –

+0

這就是我剛纔所說的。 –

+0

另一種方法是使用單獨的回調函數而不是匿名回調函數。 –

1

嘗試也傳遞$ translator作爲參數。

這可能是這樣的:

$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',create_function(
'$translator,$matches', 
'return $translator->translate($matches);'), 
$code); 

UPDATE:此代碼示例不起作用。替換回調僅用一個參數來調用,而匿名函數在這裏需要2個參數。工作實施將是:

$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',create_function(
'$matches', 
'global $translator; return $translator->translate($matches);'), 
$code); 
+0

您無法傳遞一個對象作爲回調。回調必須是一個函數。 –

+0

我打算將$ translator作爲參數傳遞給匿名函數。我會更新我的帖子以顯示代碼。 –

+0

這確實解決了'$ translator'範圍的問題,但是卻沒有正確執行。由於preg_replace_callback調用回調,它首先傳入匹配數組(並且只需要一個參數)。 –

1

在PHP 5.3中,您可以使用Closure。

<?php 
$code = preg_replace_callback(
    '/_e\(\'(.*?)\'\)/', 
    function($matches) use ($translator) { 
     return $translator->translate($matches); 
    }, 
    $code 
); 
+0

而在PHP 5.4中,閉包將能夠再次使用實例變量......等待它。 – Smar

+0

完美,謝謝。 – Programmer4me