php 在php中回显会话变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8028482/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:48:14  来源:igfitidea点击:

Echoing session variables in php

phpsession-variablessyntax-error

提问by doxguy

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?

我知道在 php 中,当我使用 echo 时,我可以将变量名放在带引号的字符串中,但显然我不能用会话变量来做到这一点。谁能解释为什么?

Here is the code, with the "offending" php commented out:

这是代码,注释掉了“违规”的 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>

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!

谢谢!

回答by Michael Berkowski

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 $_SESSIONspecifically, but any array accessed by quoted keys. Note, that you caninclude a numerically indexed array value with wrapping in {}, as in "echo $array[2] is two";

这不是特别的问题$_SESSION,而是由带引号的键访问的任何数组。请注意,您可以包含一个数字索引的数组值,并用 换行{},如"echo $array[2] is two";