Search code examples
phpstring-interpolation

How can I manually interpolate a string?


The only way I've found to interpolate a string (that is, expand the variables inside it) is the following:

$str = 'This is a $a';
$a = 'test';
echo eval('return "' . $str . '";');

Keep in mind that in a real-life scenario, the strings are created in different places, so I can't just replace 's with "s.

Is there a better way for expanding a single-quoted string without the use of eval()? I'm looking for something that PHP itself provides.

Please note: Using strtr() is just like using something like sprintf(). My question is different than the question linked to in the possible duplicate section of this question, since I am letting the string control how (that is, through what function calls or property accessors) it wants to obtain the content.


Solution

  • Here is a possible solution. I am not sure in your particular scenario if this would work for you, but it would definitely cut out the need for so many single and double quotes.

    <?php
        class a {
            function b() {
                return "World";
            }
        }
        $c = new a;
        echo eval('Hello {$c->b()}.');
    ?>