I have created a class extending SimpleXMLElement which loads an XML containing translations for a multilingual website.
In this class are two private functions - get and translate.
The former returns the translation contained in the node accessed by the xpath passed as an argument.
The latter replaces tag-like substrings in a string (eg. "Lorem ipsum #{dolor} sit amet, consectetur adipiscing elit.") with their translation obtained via
the former function - the tag being a sort of xpath I process in my get() function.
I'm using preg_replace_callback in translate() - for I cannot pass a back reference as an argument to a function in preg_replace - to send matched occurrences to get(), which will replace them with the translation.
Here is a shortened version of my class :
$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);
}
}
Of course, I get a fatal error : using $this when not in object context, for the class hasn't been instantiated in my create_function call - I tried self::get($matches[1])
as well without success.
These functions cannot be public for my class being an extension of SimpleXMLElement, it requires the path to an XML in the constructor.
So I can't do this : create_function('$matches', 'return Translation::get($matches[1]);')
.
I hope I made myself clear. The only workaround I see is passing the path to my XML in my translate() function and make it public, but this would be very inconvenient.
Do you see any other way out ?
Thanks