[英]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!" 我设置了一个全局变量$ lang($ lang ='de'),有没有办法我可以得到“ Hallo!” by using, I'm using PHP 7.3:
通过使用,我正在使用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): 实际的类(如果可以帮助或以设置的语言初始化类,我可以通过var更改const):
<?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... 这使用
global
来允许您访问您已经拥有的变量,并将其作为用于显示常量的键的一部分。
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)... 第二种方法涉及将语言设置到您的类中,因此这是一个额外的步骤,但是它也更加灵活(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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.