将PHP变量与字符串文字混合

时间:2011-03-20 13:54:57

标签: php string variables

有没有人知道更有效的方法呢?

假设我有一个变量$test,它被定义为:$test = 'cheese'

我想输出cheesey,我可以这样做:

echo $test . 'y'

但是,我更愿意将代码简化为更像这样的东西(这不起作用):

echo "$testy"

这个例子很简单,但有时我想直接在引号括起来的变量后面添加一个字符串(例如在构建MySQL查询时),并想知道是否有办法让y被视为与变量分开,而不需要将其分开。

以下示例有效,它在echo语句中读取得更好,但不是我想要的:

$test = 'cheese';
$y = 'y';
echo "$test$y";

4 个答案:

答案 0 :(得分:195)

echo "{$test}y";

直接在字符串中插入变量时,可以使用大括号来消除歧义。

此外,这不适用于单引号。所以:

echo '{$test}y';

将输出

{$test}y

答案 1 :(得分:46)

您可以在变量周围使用{},将其与之后的变量分开:

echo "{$test}y"

作为参考,您可以查看PHP手册的Variable parsing - Complex (curly) syntax部分。

答案 2 :(得分:0)

$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";

print $bucket;

的产率:

$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']

答案 3 :(得分:0)

$ test =“奶酪”; “ $ {test} y”;

它将输出 俗气

正是您想要的。