PHP vprintf中的魔术方法

时间:2017-03-31 08:29:15

标签: php magic-methods

我的PHP包含可翻译的值作为常量。通过使用常量名称调用类,应返回格式化的值。

class Test {
    const translation_value = 'Foo %s, bar %s';
    public static function __callStatic($string, $args) {
        return vsprintf(constant("self::" . $string), $args);
    }
}

如果我通过Test::{"translation_value"}(["test", "test2"]);调用该类,PHP会显示两个错误:

  

注意:第4行的数组到字符串转换[...]   PHP警告:vsprintf():第4行的参数太少[...]

我做错了什么?

如果我通过手动调用vprintf函数来测试vprintf函数(vsprintf("Foo %s, bar %s", ["val1", "val2"]);),PHP会创建预期的输出: Foo val1,bar val2

1 个答案:

答案 0 :(得分:2)

__callStatic($string, $args)的第二个参数是参数列表。你有1个参数,所以你需要使用数组的第一个元素:

return vsprintf(constant("self::" . $string), $args[0]);

或者使用平面参数调用它:

Test::translation_value("test", "test2");