Jump to content

Code Internationalization in module


Recommended Posts

https://processwire.com/api/multi-language-support/code-i18n/

In the documentation about Code Internationalization the following is mentioned:

Translatable strings

In order to make a string translatable in your template or module code, you just have to wrap the original string in a $this->_() or __() function call:

$out = $this->_("Live long and prosper");  // syntax within a class
$out = __("Live long and prosper!"); // syntax outside of a class

Inside my methods the first example of syntax in a class seems to work fine.

Somehow the following code seems to throw a 500 Internal Server Error which states:

Parse Error: syntax error, unexpected '$this' (T_VARIABLE)

Example:

class SomeModuleName extends WireData implements Module, ConfigurableModule {

    /**
     * Returns gender type
     *
     * @static
     * @return string
     */
    private static $gender = array(
        1 => $this->_("Male"),
        2 => $this->_("Female"),
    );
}

I can image since the module is not initialized or constructed yet that $this is not available at that spot.

Any tips on how to be able to make those values multilanguage?

Link to comment
Share on other sites

As Martijn said, $this can never be used in a static context (ok in PHP actually it's possible but very dangerous).

You could move the initialization with the translations into the constructor, it should work:

class SomeModuleName extends WireData implements Module, ConfigurableModule {

    /**
     * Returns gender type
     *
     * @static
     * @return string
     */
    private static $gender = array();

    
    public function __construct() {
        self::$gender = array(
           1 => $this->_("Male"),
           2 => $this->_("Female"),
        );
    }
}
  • Like 5
Link to comment
Share on other sites

As Martijn said, $this can never be used in a static context (ok in PHP actually it's possible but very dangerous).

You could move the initialization with the translations into the constructor, it should work:

class SomeModuleName extends WireData implements Module, ConfigurableModule {

    /**
     * Returns gender type
     *
     * @static
     * @return string
     */
    private static $gender = array();

    
    public function __construct() {
        self::$gender = array(
           1 => $this->_("Male"),
           2 => $this->_("Female"),
        );
    }
}

Thanks wanze, your example works great!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...