views:

250

answers:

1

Good evening,

In my app that I'm currently developing, I have a class that handles multilinguism. It does so by externally loading an associative array, where a translation source would be defined something like this:

'Source input' => 'Zdroj vstupního'

Currently this works flawlessly by addressing and using the class the following way:

$lang = new Lang('Czech');
print $lang->_('Source input'); // output: "zdroj vstupního"

However, I want to have this in a short cut function that does not depend on an instance of the "Lang" class. I've tried experimenting with static methods, but so far I'm out of luck.

Pseudo code of what I want to achieve.

 $lang = new Lang('Czech');
 $lang->setCurrent('contact_us'); // loads the language file for contact_us
 <p>
   <?php print _('Source input'); ?> // output: "zdroj vstupního"
 </p>

A point in the right direction would be great. Thanks!

+2  A: 

You can access the global $lang variable from your _ function if you use a global $lang statement:

<?php
    class Lang
    {
        function _($str)
        {
            return 'Zdroj vstupního';
        }
    }

    function _($str)
    {
        global $lang;
        return $lang->_($str);
    }

    $lang = new Lang('Czech');
    print _('Source input');
?>

Alternatively you could use a static variable in the Lang class instead of creating an instance of the class. It's a little cleaner this way as you avoid having to create a $lang variable in the global namespace.

<?php
    class Lang
    {
        static $lang;

        function setCurrent($lang)
        {
            self::$lang = $lang;
        }
    }

    function _($str)
    {
        if (Lang::$lang == 'Czech')
        {
            return 'Zdroj vstupního';
        }
    }

    Lang::setCurrent('Czech');
    print _('Source input');
?>
John Kugelman
The best answer I could get. Many, many thanks John! :-)
loathsome