2012-02-10 75 views
2

我創建延伸的SimpleXMLElement其加載包含多語言的網站翻譯的XML類。 這個類是兩個私有函數 - 獲取和翻譯。 前者返回包含在由作爲參數傳遞的xpath訪問的節點中的翻譯。

後者替換字符串中的標籤狀子字符串(例如,「Lorem ipsum#{dolor} sit amet,consectetur adipiscing elit。」),其翻譯是通過 獲得的前一個函數 - 標記是一種xpath I在我的get()函數中進行處理。

我使用preg_replace_callback在翻譯() - 因爲我不能在preg_replace函數後引用作爲參數傳遞給函數 - 發送匹配的事件得到(),這將翻譯替換它們。PHP OOP調用私有函數回調在create_function

這裏是我的類的縮短版:

$translation = new Translation('path_to_my_xml', null, true); 

class Translation extends SimpleXMLElement { 
    function get($xpath){ 
     // xpath is of the form 'parent_node/child_node' 
     // After some processing and the wanted node being found - it returns the translation 
    } 

    function translate($string){ 
     $string = preg_replace_callback('/#\{([a-z0-9-\/]+)\}/', create_function('$matches', 'return $this->get($matches[1]);'), $string); 
    } 
} 

當然,我得到一個致命的錯誤:使用$這個時候不是在目標範圍內,爲班級沒有出現在我的create_function呼叫實例 - 我試過self::get($matches[1])也沒有成功。
這些功能不能公開我的課是的SimpleXMLElement的延伸,它要求的路徑,在構造函數中的XML。 所以我不能這樣做:create_function('$matches', 'return Translation::get($matches[1]);')

我希望我明確自己。我看到的唯一解決方法是將我的translate()函數中的路徑傳遞給我的XML並將其公開,但這會非常不方便。 你有沒有看到其他出路?

感謝

回答

3

掛上,你不能只使用一箇舊式數組的PHP回調像這樣嗎?

function translate($string){ 
    $string = preg_replace_callback('/#\{([a-z0-9-\/]+)\}/', 
            array($this, 'translateCallback'), 
            $string); 
} 

public function translateCallback($matches) 
{ 
    return return $this->get($matches[1]); 
} 
+0

感謝羅布,它完美的作品。爲什麼這麼簡單的方法,當你可以很難做到的時候,humm?我只是不知道你可以使用數組作爲回調。 – rgandoin 2012-02-10 15:22:55

0

設施使用$這在lambda /匿名函數在PHP 5.4中添加,懷疑這是相似的;但我不得不跑上我的測試平臺來檢查。

你可以嘗試:

$string = preg_replace_callback('/#\{([a-z0-9-\/]+)\}/', function($matches) use ($this) { return $this->get($matches[1]); }, $string); 
+0

我在PHP 5.2上,但是要感謝你們兩個人的嘗試。 – rgandoin 2012-02-10 14:56:34

0

可能不是非常有幫助的,但是在PHP 5.4匿名函數可以訪問$this。你的發貨日期是什麼時候?

+0

不幸的是,我在PHP 5.2上運行。 – rgandoin 2012-02-10 14:55:54

+0

你可以升級嗎? – Flukey 2012-02-10 15:05:24

2

1:

preg_replace_callback($regexp, array($this, 'someMethod'), $string) 

2:

$myFunc = function($matches) use ($this) ... 
... 
preg_replace_callback('/#\{([a-z0-9-\/]+)\}/', $myFunc, $string) 

3:在翻譯中保存最後一個實例 覆蓋__construct,實現翻譯:: getLastInstance(),並用它裏面create_function或實現翻譯: :get($ m)使用最後一個實例,並將其作爲數組(preR_replace_callback)傳遞給array('Translation','get'),或者在將preg_replace_callback連接到當前實例之前保存到self :: $ currentInstance中。 在任何情況下,sence是在保存一個鏈接到實例的靜態屬性翻譯