PHP - 如何将命名变量放在字符串中使用在变量之前定义的字符串

Tho*_*ner 2 php

我正在寻找相当于pythons %运算符的php .

# PYTHON Example
foo = 'variable_string'
baz = 'characters'

new_string = 'my %(foo)s of %(baz)s' % locals()
Run Code Online (Sandbox Code Playgroud)

我模糊的php上下文:

注意:这是为了说明我为什么要这样做,它不反映任何代码.

// PHP Example context
class Controller {
    ...
    // Singles quotes used in intentionally
    // This template string is meant to be overloadable.
    public $template = '<h1>{$title}</h1><h2>{$subheading}</h2>'; 
    ....
}

class View {
    ...
    public function render($template) {
        $title = 'variable string';
        $subheading = 'some other variable stuff';
        // Example of the python operator
        return magically_put_variables_in_string(
            $template, 
            magically_get_named_variables_from_scope()
        );
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)
  • 具体来说,我想要最规范的magically_put_variables_in_string实现.
  • 我不能假设我能够使用晚于php 5.3的任何东西
  • 我不介意传递一个明确的 array('$variable_name' => $variable_name)
  • 没有定义新功能的要点.

最后注意:我已经为我的特定用例构建了一个解决方案,但它不能满足这个问题.

DCo*_*der 12

一个好方法是strtr:

strtr('<h1>{foo}</h1><h2>{bar}</h2>', array(
  '{foo}' => $foo,
  '{bar}' => $bar,
));
Run Code Online (Sandbox Code Playgroud)

您还可以使用get_defined_vars()获取当前作用域中可访问的变量数组,但我个人更喜欢显式枚举.


对使用的细微优点strtrstr_replacestrtr搜索的字符串的已取代的部分,用于进一步的替代品.str_replace州的手册页:

因为str_replace()从左到右替换,所以在执行多次替换时,它可能会替换先前插入的值.