我創建延伸的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並將其公開,但這會非常不方便。 你有沒有看到其他出路?
感謝
感謝羅布,它完美的作品。爲什麼這麼簡單的方法,當你可以很難做到的時候,humm?我只是不知道你可以使用數組作爲回調。 – rgandoin 2012-02-10 15:22:55