![](/img/trans.png)
[英]Is it standard to use “Defined Constant as a prefix for a function name” or a “Variable Function” in PHP?
[英]PHP pass a variable to Class and use it as prefix for constant or variable
我設置了一個全局變量$ lang($ lang ='de'),有沒有辦法我可以得到“ Hallo!” 通過使用,我正在使用PHP 7.3:
L::HELLO('Mike');?
我不是在尋找像這樣的解決方案:
sprintf(constant('L::' . $lang . '_HELLO'), 'Mike');
而是只通過調用它們來獲得它們:
L::HELLO('Mike');
要么:
L::HI;
實際的類(如果可以幫助或以設置的語言初始化類,我可以通過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);
}
}
我可以通過兩種方式查看。 首先是最簡單的-但通常我也不會推薦它。
這使用global
來允許您訪問您已經擁有的變量,並將其作為用於顯示常量的鍵的一部分。
public static function __callStatic($string, $args) {
global $lang;
return vsprintf(constant("self::" .$lang."_" . $string), $args);
}
所以
$lang = "de";
echo L::HELLO('Mike');
給
Hallo Mike!
第二種方法涉及將語言設置到您的類中,因此這是一個額外的步驟,但是它也更加靈活(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);
}
}
因此,您將其用作...
$lang = "de";
L::setLang($lang);
echo L::HELLO('Mike');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.