简体   繁体   中英

PHP pass a variable to Class and use it as prefix for constant or variable

I have set a global variable $lang ($lang = 'de'), is there a way how I could get "Hallo!" by using, I'm using PHP 7.3:

L::HELLO('Mike');?

I'm not looking for a solution like:

sprintf(constant('L::' . $lang . '_HELLO'), 'Mike');

instead to got them by calling only:

L::HELLO('Mike');

or:

L::HI;

actual Class (I can change const by var if this would help or initiate class with set language):

<?php class L {
    const en_HELLO = 'Hello %s!';
    const de_HELLO = 'Hallo %s!';
    const fr_HELLO = 'Bonjour %s!';
    const it_HELLO = 'Ciao %s!';
    const en_HI = 'Hi...';
    const de_HI = 'Hi...';
    const fr_HI = 'Hi...';
    const it_HI = 'Hi...';

    public static function __callStatic($string, $args) {
        return vsprintf(constant("self::" . $string), $args);
    }
}

There are two ways I can see for this. The first is the simplest - but also I would normally not recommend it.

This uses global to allow you to access the variable you already have and includes it as part of the key used to display the constant...

public static function __callStatic($string, $args) {
    global $lang;
    return vsprintf(constant("self::" .$lang."_" . $string), $args);
}

So

$lang = "de";
echo L::HELLO('Mike');

gives

Hallo Mike!

The second method involves setting the language into your class, so it's an extra step, but it's also more flexible (IMHO)...

class L {
    const en_HELLO = 'Hello %s!';
    const de_HELLO = 'Hallo %s!';
    const fr_HELLO = 'Bonjour %s!';
    const it_HELLO = 'Ciao %s!';

    protected static $lang = "en";

    public static function setLang ( string $lang )  {
        self::$lang = $lang;
    }

    public static function __callStatic($string, $args) {
        return vsprintf(constant("self::" .self::$lang."_" . $string), $args);
    }
}

So then you use it as...

$lang = "de";
L::setLang($lang);
echo L::HELLO('Mike');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM