[英]PHP how I can pass arguments to constant
I'm looking for a solution to pass arguments to a dynamic constant Name. 我正在寻找一个将参数传递给动态常量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);
}
}
My code 我的代码
$x = 1;
echo constant("L::profile_tag_".$x); // arguments: 20, 30
I want get 我想得到
Bla bla Age from 20 to 30
How can I pass my two arguments to it? 我怎样才能将我的两个论点传递给它?
You can use func_get_args()
and array_shift()
to isolate the constant string name. 您可以使用
func_get_args()
和array_shift()
来隔离常量字符串名称。
[ Codepad live ] [ 键盘直播 ]
<?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);
But, be aware when using this function with a generic call to a static method, you need to change __callStatic
signature to allow $name
and $arguments
like this: 但是,请注意当使用此函数与静态方法的泛型调用时,您需要更改
__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);
Although, there is a better way to perform what you need (read Yoshi in comments), considering you are using everything static: 虽然,有一种更好的方法来执行你需要的东西(在评论中阅读Yoshi),考虑到你正在使用静态的东西:
echo sprintf(L::profile_tag_1,12,14);
You don't even need a Class
at this point. 此时你甚至不需要一个
Class
。
试试这个:
echo L::__callStatic("profile_tag_".$x, array(20, 30));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.