I've been trying to create a string literals file for PHP, so I can hold all of my strings in one file.
I was wondering if it was good practice to do something like:
class Literals
{
const String1 = "Hello";
const String2 = "World!";
//... (up开发者_StackOverflow中文版 to 100+ literals)...
}
And then somewhere in my code I could call it like:
$hello = Literals::String1;
Is this good practice?
It depends on what you're going to do with the strings. If you're going to display them to the user, then sure, it's a simple way of doing internationalization, although you'll want to look at something more advanced if you're going to do a lot of it. If you're just going to use them for associative array keys, database column names or other internal things, then no, just keep them inline.
Hopefully you did not really call them String1...StringN :)
If for localization I personally would prefer this one (as used by Apple):
In code use something like:
<h1><?php localize("Homepage","String for the homepage") ?></h1>
.
function localize($key,$help='') {
//do a lookup of the key and if not found use the key itself
}
Then you can use a parser to find all strings and create a reference translation:
$strings = array(
/** String for the homepage */
'Homepage' => 'Homepage'
);
This has the advantage that the main language version will always work and other translations can be added when needed. It's disadvantage is that you need a parser to find all strings.
精彩评论