Let's say you are building a multilingual web application in which all interface text should be moved to language-dependent resources and loaded when needed. The string resource may be huge: say you have several thousands of strings translated. In windowed environments (Windows, OS X, X11) you usually have a mechanism provided by the OS or some API for doing just that and they are usually called string resources. What about PHP then?
Remember though, performance must be considered seriously here as PHP compiles and executes all your modules with each user request.
I can think of several possible ways of doing it. But first of all, I'm going to have a global variable $LANGUAGE which may be set to 'en', 'de', 'fr' etc. I'll use this variable to include a language-specific module with each request as
require_once "lang-$LANGUAGE.inc.php"
So some of the possible solutions include:
(1) Defining all strings as global vars in each language module, e.g.
$str_signin = 'Sign in';
$str_welcome_user = 'Welcome, %s'!;
...
Very simple, easy to read and relatively easy to work on for non-technical people (translators, that is). There is some global space pollution though which will slow down your global variable lookup a bit.
(2) Same but defined as one huge array, e.g.
$str['signin'] = 'Sign in';
$str['welcome_user'] = 'Welcome, %s'!;
...
Less readable, a bit less usable in your main code (more typing involved) also clutters your code a bit more. This would be slower because these are not simple assignments but assoc. array assignments: there will be more instructions to execute here for the VM compared to (1).
(3) PHP 5.3+: define as constants, possibly in a class or namespace
class str {
const signin = 'Sign in';
const welcome_user = 'Welcome, %s'!;
const signin_to_a = self::signin . ' to area A'; // can't do this!
...
}
... and use them as str::signin etc. Nice, I like this most of all, although there are a few minor disadvantages as well: PHP 5.3+ only; can't use expressions, only single values (which may or may not be fine in your case); can't use in $-expansion in double-quoted strings (or can you?).
(4) Database: put everything into a table and retrieve by some ID, e.g. str_get(STR_SIGNIN). Ugly, slow, needs syncing of your ID's in the code with the DB ID's, however no need to load everything when all your page needs is just a few strings. Honestly can't say if this is a good solution or not.
Any other suggestions? Also, thoughts on these ones?
And please do keep in mind simplicity, elegancy and performance!