2013-04-01 36 views
0

我使用下面张贴的PHP手册应该让我用一个字符串中的方法调用的返回值的例子...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

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

+0

给$ Bob分配一个值,你就会很好...... – zgr024

+0

如果你打算用方法调用来构建字符串,我建议将它们分配给一个变量,或者至少保持方法调用不在字符串之外本身。它会变得混乱(正如你所看到的...)。 – Phix

回答

2

你现在有这样的:

"... {$getName()}" 

这意味着PHP运行getName()功能,得到Bob回来,然后写着:

"... {$Bob}" 

现在,他正试图让变量$Bob (因为变量是用双引号分析的)。

的解决方案是使用单引号,把函数调用的字符串外:

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

或者逃避它:

​​
+1

替代地,有可变的功能。 '$ x ='getName';回声“{$ x()}”;'。不是我推荐使用它们,但它们偶尔派上用场。 –

+0

@MarcB是工作,对我来说,它看起来会尝试调用'x()',然后''' –

+1

nope。 php将首先扩展$ x,所以它变成“{getName()}”,然后执行getName函数。然而,使用文字'echo“{getName()}”'不起作用 - 它只适用于变量扩展。 –

1

你可以不喜欢这样,它应该做你inteded

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

function getName() 
{ 
    return "Bob";  
} 

希望这是帮助您

+0

我知道,但我想从头开始理解php更好。手册说这应该是可能的,并提供这个例子 –