将 PHP 变量与字符串文字混合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5368890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mixing a PHP variable with a string literal
提问by Matt McDonald
Say I have a variable $test
and it's defined as: $test = 'cheese'
假设我有一个变量$test
,它被定义为:$test = 'cheese'
I want to output cheesey
, which I can do like this:
我想输出cheesey
,我可以这样做:
echo $test . 'y'
But I would prefer to simplify the code to something more like this (which wouldn't work):
但我更愿意将代码简化为更像这样的东西(这是行不通的):
echo "$testy"
Is there a way to have the y
be treated as though it were separate from the variable?
有没有办法让y
变量被视为与变量分开?
回答by alex
echo "{$test}y";
You can use braces to remove ambiguity when interpolating variables directly in strings.
在字符串中直接插入变量时,您可以使用大括号来消除歧义。
Also, this doesn't work with single quotes. So:
此外,这不适用于单引号。所以:
echo '{$test}y';
will output
会输出
{$test}y
回答by Pascal MARTIN
You can use {}
arround your variable, to separate it from what's after:
您可以使用{}
arround 您的变量,将其与后面的内容分开:
echo "{$test}y"
As reference, you can take a look to the Variable parsing - Complex (curly) syntaxsection of the PHP manual.
作为参考,您可以查看PHP 手册的变量解析 - 复杂(卷曲)语法部分。
回答by Rizwan
Example:
例子:
$test = "chees";
"${test}y";
It will output:
它会输出:
cheesy
俗气的
It is exactly what you are looking for.
这正是您要寻找的。
回答by earlyburg
$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";
print $bucket;
yields:
产量:
$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']