开发者

A strange question about echo output

Look at the code below

echo "$_SERVER['HTTP_HOST开发者_开发问答']";

it show 'Parse error', while the next shows ok

$str = $_SERVER['HTTP_HOST'];
echo "$str";

That was very strange to me.


to refer an associative array inside of a string, you have to either add curly braces or remove quotes:
both

echo "{$_SERVER['HTTP_HOST']}";
echo "$_SERVER[HTTP_HOST]";

would work

http://php.net/manual/en/language.types.string.php <- extremely useful reading


in this case, you should use bracket to point out the variable range in string

echo "{$_SERVER['HTTP_HOST']}";

see also http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double


As you have discovered, referring to variables inside a string literal is error-prone and should be avoided. Separate string literals from variables, and use single quotes whenever possible:

echo 'Host: header: ' . $_SERVER['HTTP_HOST'] . "\n";

If you really want to use complex variable expressions inside string literals (and you shouldn't!), remove the inner quotes:

echo "Host header: $_SERVER[HTTP_HOST]";

or surround the variable reference inside curly braces:

echo "Host header: {$_SERVER['HTTP_HOST']}";


If a variable is detected in a double-quoted string, it will automaticly be converted to it's string value. But that's not every your case. the fact that the key of your array is also a string comes in conflict with the php parser. ex :

$ar = array("key" => "val");
echo "$ar['key']"; // won't work
echo "$ar[0]"; // will work because the key is not a string

Anyway, like others already said, the best solution is to encapsulate your variable in curly braces :

echo "{$ar['key']}"; 


it should be

echo $_SERVER['HTTP_HOST'];

if you want to output $_SERVER['HTTP_HOST'], escape that dollar sign

echo "\$_SERVER['HTTP_HOST']";

or put it into single quote

echo '$_SERVER["HTTP_HOST"]';

Clarification: You should not put only variables into quotes if you want content of actual variable, just delete these quotes and it will work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜