如何手动插入字符串? [英] How can I manually interpolate a string?

查看:99
本文介绍了如何手动插入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现插入字符串(即扩展其中的变量)的唯一方法是:

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 . '";');

请记住,在实际情况下,字符串是在不同的位置创建的,所以我不能仅将' s替换为" s.

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.

是否有更好的方法可以在不使用eval()的情况下扩展单引号字符串?我正在寻找PHP本身提供的东西.

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.

请注意:使用 strtr()就像使用 sprintf()之类的东西一样.我的问题与该问题的可能重复部分中链接的问题不同,因为我让字符串控制它想要(即通过什么函数调用或属性访问器)获取内容的方式.

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.

推荐答案

这是一个可能的解决方案.我不确定在您的特定情况下这是否适合您,但肯定会消除对这么多单引号和双引号的需要.

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()}.');
?>

这篇关于如何手动插入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆