Mat*_*ald 128 php string variables
有谁知道更有效的方法吗?
假设我有一个变量$test,它被定义为:$test = 'cheese'
我想输出cheesey,我可以这样做:
echo $test . 'y'
Run Code Online (Sandbox Code Playgroud)
但是,我更愿意将代码简化为更像这样的东西(这不起作用):
echo "$testy"
Run Code Online (Sandbox Code Playgroud)
这个例子很简单,但有时我想在一个变量之后直接添加一个字符串,这个变量我已经用引号括起来了(例如在构建一个MySQL查询时),并想知道是否有办法y让它被视为与它分开变量,无需分离它.
以下示例有效,它在echo语句中读取得更好,但不是我想要的:
$test = 'cheese';
$y = 'y';
echo "$test$y";
Run Code Online (Sandbox Code Playgroud)
ale*_*lex 212
echo "{$test}y";
Run Code Online (Sandbox Code Playgroud)
在直接在字符串中插入变量时,可以使用大括号来消除歧义.
此外,这不适用于单引号.所以:
echo '{$test}y';
Run Code Online (Sandbox Code Playgroud)
将输出
{$test}y
Run Code Online (Sandbox Code Playgroud)
Pas*_*TIN 47
您可以使用{}变量的arround,将其与之后的变量分开:
echo "{$test}y"
Run Code Online (Sandbox Code Playgroud)
作为参考,您可以查看PHP手册的变量解析 - 复杂(卷曲)语法部分.