在php中回显会话变量

发布于 2024-12-14 08:27:03 字数 1058 浏览 4 评论 0原文

我知道在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋日私语 2024-12-21 08:27:03

在双引号字符串内,您必须将复杂变量(数组或对象属性)括在 {} 中:

<p><?php echo("{$_SESSION['test']}"."<br />");?></p>

这不是 $_SESSION 的具体问题,而是任何数组的问题通过带引号的键访问。请注意,您可以包含一个用 {} 包装的数字索引数组值,如 "echo $array[2] is Two";

Inside a double-quoted string you must enclose a complex variable (array or object property) in {}:

<p><?php echo("{$_SESSION['test']}"."<br />");?></p>

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";

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文