Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The most often used solution is a strings file. E.g. like following:</p> <pre><code># library class Foo { public function __construct($lang = 'en') { $this-&gt;strings = require('path/to/langfile.' . $lang . '.php'); $this-&gt;message = $this-&gt;strings['callMeToo']; } public function callMeToo($user) { return sprintf($this-&gt;strings['callMeToo'], $user); } } # strings file return Array( 'callMeToo' =&gt; 'Hi %s, nice to meet you!' ); </code></pre> <p>You can, to avoid the <code>$this-&gt;message</code> assignment, also work with magic getters:</p> <pre><code># library again class Foo { # … code from above function __get($name) { if(!empty($this-&gt;strings[$name])) { return $this-&gt;strings[$name]; } return null; } } </code></pre> <p>You can even add a <code>loadStrings</code> method which takes an array of strings from the user and merge it with your internal strings table.</p> <p>Edit 1: To achieve more flexibility I would change the above approach a little bit. I would add a translation function as object attribute and always call this when I want to localize a string. The default function just looks up the string in the strings table and returns the value itself if it can't find a localized string, just like gettext. The developer using your library could then change the function to his own provided to do a completely different approach of localization.</p> <p>Date localization is not a problem. Setting the locale is a matter of the software your library is used in. The format itself is a localized string, e.g. <code>$this-&gt;translate('%Y-%m-%d')</code> would return a localized version of the date format string.</p> <p>Number localization is done by setting the right locale and using functions like <code>sprintf()</code>.</p> <p>Currency localization is a problem, though. I think the best approach would be to add a currency translation function (and, maybe for better flexibility, another number formatting function, too) which a developer could overwrite if he wants to change the currency format. Alternatively you could implement format strings for currencies, too. For example <code>%CUR %.02f</code> – in this example you would replace <code>%CUR</code> with the currency symbol. Currency symbols itself are localized strings, too.</p> <p>Edit 2: If you don't want to use <code>setlocale</code> you have to do a lot of work… basically you have to rewrite <code>strftime()</code> and <code>sprintf()</code> to achieve localized dates and numbers. Of course possible, but a lot of work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload