您可以使用func_get_args()和array_shift()来隔离常量字符串名称.
[
Codepad live]
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);
此时你甚至不需要一个班级.