php 字符串加变量,将变量放入字符串PHP

这篇博客讨论了在 Laravel 框架中遇到的一个问题,即使用单引号和双引号在 return redirect() 语句中进行变量插值的区别。作者作为 Laravel 新手,发现双引号允许直接解析变量,而单引号则需要使用字符串连接。解决方案是使用双引号或通过字符串连接来插入变量。博客还提到了 PHP 的字符串插值原理,并引用了相关资源来说明单引号和双引号的性能差异。
摘要由CSDN通过智能技术生成

我是Laravel的新手,我有这个问题。

我尝试了以下代码行,并且工作正常:return redirect("/cards/{$note->id}");

但是,无论何时我尝试使用单引号,它都不起作用:return redirect('/cards/{$note->id}');

我怎么解决这个问题 ?

使用cards. $note->id

与laravel无关,它的基本php内容单引号和双引号

我是新来的,我认为拉拉维(Laravel)可以用自己的方式做这些事情

您首先要做的就是变量插值或字符串插值。 您可以在PHP文档和Wiki上阅读有关它的更多信息。

这是PHP中的一项功能,它允许您传递字符串并在内部解释变量/占位符。

在第二个示例中,您使用的单引号不提供此功能,因此您必须将其分解并将变量手动添加到字符串中:

return redirect('/cards/' . $note->id);

如果您对更详尽的解释及其背后的表现感兴趣,可以在Blizz的此处阅读有关此答案的更多信息。

他的结论是:

Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.

However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.

您应该使用"/cards/{$note->id}"或'/cards/'.$note->id

The most important feature of double-quoted strings is the fact that variable names will be expanded.

When a string is specified in double quotes or with heredoc, variables are parsed within it.

从PHP文档

花括号是字符串插值的一部分,完全不应包含在单引号中。

像这样使用它:

return redirect('/cards/'. $note->id);

用单引号或双引号

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值