在php中回显会话变量
我知道在 php 中,当我使用 echo 时,我可以将变量名放在带引号的字符串中,但我显然不能使用会话变量来执行此操作。谁能解释为什么?
这是代码,注释掉了“有问题的”php:
<?php
session_start();
$test = 100;
$_SESSION['test'] = 200;
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<p><?php echo($test."<br />");?></p>
<p><?php echo("$test"."<br />");?></p>
<p><?php echo($_SESSION['test']."<br />");?></p>
<p><?php //echo("$_SESSION['test']"."<br />");?></p>
</body>
</html>
输出如下所示:
100
100
200
但是如果我取消注释有问题的代码行:
<p><?php echo("$_SESSION['test']"."<br />");?></p>
我没有得到任何输出并出现以下错误:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in - on line 14
所以我可以继续我的快乐方式知道如何正确地执行此操作(只需将会话变量放在双引号之外),但我真的很想了解为什么这对会话变量不起作用。
谢谢!
I know that in php I can put a variable name inside a quoted string when I use echo, but I apparently can't do this with a session variable. Can anyone explain why?
Here is the code, with the "offending" php commented out:
<?php
session_start();
$test = 100;
$_SESSION['test'] = 200;
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<p><?php echo($test."<br />");?></p>
<p><?php echo("$test"."<br />");?></p>
<p><?php echo($_SESSION['test']."<br />");?></p>
<p><?php //echo("$_SESSION['test']"."<br />");?></p>
</body>
</html>
And the output looks like this:
100
100
200
But if I uncomment the offending code line:
<p><?php echo("$_SESSION['test']"."<br />");?></p>
I get no output and the following error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in - on line 14
So I can go on my merry way knowing how to do it correctly (just keep the session variable outside of the double quotes), but I would really like to understand why this doesn't work for session variables.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在双引号字符串内,您必须将复杂变量(数组或对象属性)括在
{}
中:这不是
$_SESSION
的具体问题,而是任何数组的问题通过带引号的键访问。请注意,您可以包含一个用{}
包装的数字索引数组值,如"echo $array[2] is Two";
Inside a double-quoted string you must enclose a complex variable (array or object property) in
{}
:This isn't an issue with
$_SESSION
specifically, but any array accessed by quoted keys. Note, that you can include a numerically indexed array value with wrapping in{}
, as in"echo $array[2] is two";