[英]Can I pass a DEFINED constant to a function through a variable in PHP?
[英]PHP how I can pass arguments to constant
我正在尋找一個將參數傳遞給動態常量Name的解決方案。
<?php
class L {
const profile_tag_1 = 'Bla bla Age from %s to %s';
const profile_tag_2 = 'Wow Wow Age from %s to %s';
public static function __callStatic($string, $args) {
return vsprintf(constant("self::" . $string), $args);
}
}
我的代碼
$x = 1;
echo constant("L::profile_tag_".$x); // arguments: 20, 30
我想得到
Bla bla Age from 20 to 30
我怎樣才能將我的兩個論點傳遞給它?
您可以使用func_get_args()
和array_shift()
來隔離常量字符串名稱。
[ 鍵盤直播 ]
<?php
class L {
const profile_tag_1 = 'Bla bla Age from %s to %s';
const profile_tag_2 = 'Wow Wow Age from %s to %s';
public static function __callStatic() {
$args = func_get_args();
$string = array_shift($args);
return vsprintf(constant('self::' . $string), $args);
}
}
L::__callStatic('profile_tag_1',12,12);
但是,請注意當使用此函數與靜態方法的泛型調用時,您需要更改__callStatic
簽名以允許$name
和$arguments
如下所示:
class L {
const profile_tag_1 = 'Bla bla Age from %s to %s';
const profile_tag_2 = 'Wow Wow Age from %s to %s';
public static function __callStatic($name, $args) {
$string = array_shift($args);
return vsprintf(constant('self::' . $string), $args);
}
}
L::format('profile_tag_1',12,12);
雖然,有一種更好的方法來執行你需要的東西(在評論中閱讀Yoshi),考慮到你正在使用靜態的東西:
echo sprintf(L::profile_tag_1,12,14);
此時你甚至不需要一個Class
。
試試這個:
echo L::__callStatic("profile_tag_".$x, array(20, 30));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.