Most efficient way to do language file in PHP?

前端 未结 9 1871
日久生厌
日久生厌 2020-12-04 14:39

Questions Updated instead of making a new question...

I really want to provide a few alternative languages other then English on my social network s

9条回答
  •  春和景丽
    2020-12-04 15:15

    An extension to the answers above whom deserve the credit - I'm just posting as maybe this will also be useful to someone else who ends up here.

    I personally prefer the key to the array to be the actual phrase in my mother tongue (in my case English) rather than a CONSTANT_VALUE because:

    • I find it easier to read the code when the text is in my native language rather than having to remember what a CONSTANT_VALUE actually outputs
    • It means no lookup is needed to return the phrase for visitors who also use my naitive language (giving marginally better performance)
    • It's one less list of values to maintain

    The downside is that it's harder to spot missing values in other languages as you don't necessarily have a master list anymore - I also log a warning from the abstract method so that I spot any missing values.

    I implemented as:

    • An abstract class with static methods for outputting the text value (using late static binding)
    • A concrete class for each language: English overriding the method to return the phrase without translation, other languages overriding the list of phrases so that a translated phrase is returned
        
        
         'Nombre',
                'Registered Email' => 'Correo electrónico registrado',
                'Surname' => 'Apellido'
            );
        }
    

    Usage:

        $language = new \Language\Spanish();
        echo $language::output('Forename'); // Outputs: Nombre
    
        $language = new \Language\English();
        echo $language::output('Registered Email'); // Outputs: Registered Email
    

提交回复
热议问题