PHP字符串-字符串内部的方法调用不像manual那样工作


PHP Strings - method call inside string doesnt work as in manual

我使用以下作为php手册上发布的示例,应该允许我在字符串中使用方法调用的返回值…

echo "This is the value of the var named by the return value of getName(): {${getName()}}";
function getName()
{
    return "Bob";    
}

然而,我得到一个错误:" Notice: Undefined variable: Bob "

这个例子来自php手册:http://php.net/manual/en/language.types.string.php

是手册错误还是我在这里做错了什么?

你现在有了:

"... {$getName()}"

这意味着PHP正在运行getName()函数,获取Bob,然后读取:

"... {$Bob}"

现在,他正试图获得变量$Bob(因为变量在双引号中解析)。

解决方案是使用单引号并将函数调用放在字符串之外:

'... {$'.getName().'}'

或者转义:

"... '{'$getName()'}"

你可以这样做,它应该做你想要的

echo "This is the value of the var named by the return value of ".getName();
function getName()
{
    return "Bob";    
}

希望这对你有帮助