{$ variable}如何在PHP中运行?

时间:2011-02-28 04:50:56

标签: php string variables interpolation

当我想在字符串中使用变量值时,我将它们连接起来。 (点)运算符。

我看到有些人在字符串中使用{$ variable}。

所以......我的例子:

"my name is ".$variable
有些人使用它:

"my name is {$variable}"

上述两个例子有什么区别?

2 个答案:

答案 0 :(得分:12)

当你想在字符串中的变量中附加一个字符串时使用它。

$variable = 'hack';

// now I want to append 'ed' to $variable:    

echo "my name is {$variable}";   // prints my name is hack

echo "my name is {$variable}ed"; // prints my name is hacked

echo "my name is $variable";     // prints my name is hack

echo "my name is $variableed";   // Variable $variableed not defined.

答案 1 :(得分:2)

也许一些例子可以解释括号和。运算符以连接字符串。

假设你有一个变量持有一些价值,比如$ money,你想显示这个数额。

$money=10;

print "you have earned $money"; // would output 'you have earned 10;
// ops missed the dollar sign as we are dealing with currency.
print "you have earned $$money"; // hmmm, that wont work $$ means something else.

因此,如果你有花括号,那么你可以告诉PHP你想要更清楚地将哪个变量替换成字符串。

print "you have earned ${$money}.00"; would now output 'you have earned $10.00'

现在看起来好多了。