4

有没有办法为以后的插值“准备”一个字符串(不使用自定义扩展函数)?
例如:

class Test {
    private static $STR_VAL = "the val is $v";

    public static function printVal($v) {
        echo self::$STR_VAL;
    }
}
4

2 回答 2

8

sprintf()

class Test {
    private static $STR_VAL = "the val is %s";

    public static function printVal($v) {
        echo sprintf(self::$STR_VAL, $v);
    }
}
于 2012-07-06T09:44:24.697 回答
0

如果要保留实际变量插值的解决方案:

function interpolate_string($string, $vars) {
    extract($vars);
    return eval('return "' . addslashes($string) . '";');
}

class Test {
    //Note the single quote to prevent interpolation here
    private static $STR_VAL = 'the val is $v'; 

    public static function printVal($v) {
        echo interpolate_string(self::$STR_VAL, compact('v'));
    }
}

虽然我在这段特定代码中没有看到任何明显的攻击,但应该注意的是,在处理不受信任的字符串时,使用eval()可能是代码注入的载体。

于 2018-01-10T22:02:04.390 回答