{$variable} 在 PHP 中如何工作?

发布于 2024-10-19 15:39:12 字数 229 浏览 0 评论 0原文

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

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

所以..我的例子:

"my name is ".$variable

有些人使用它:

"my name is {$variable}"

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

When I want to use a variable value within a string, I connect them with . (dot) operator.

I see that some people use {$variable} within a string instead.

So..my example:

"my name is ".$variable

some people use it:

"my name is {$variable}"

What is the difference between above two examples?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小伙你站住 2024-10-26 15:39: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.

It's used when you want to append a string to the value in the variable inside a string.

$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.
彻夜缠绵 2024-10-26 15:39:12

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

假设您有一个变量保存某个值,即 $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'

现在看起来好多了。

Maybe some examples will explain the brackets and the . operator to concatenate strings.

Lets say you have a variable holding some value which is say $money and you want to display this amount.

$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.

So if you have curly braces then you can tell PHP which variable you want substituted into the string a lot more clearly.

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

Now that looks a lot nicer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文