if之间的变量,否则条件

时间:2014-02-09 12:33:34

标签: php

我想在两个if / else条件块之间使用一个变量。

if(isset($_GET['aaa']))
{
  code to be executed;
  $example='a string or codes(calculating)';
}
else  //if(isset($_GET['bbb']))
{
  code to be executed;
}

我如何在else子句中使用$ example?解释一下,例如,在第一次if子句为真并计算$ example时,对于第二次加载,否则为true,现在我想使用$ example。我将$ example声明为静态变量,但它不起作用。 谢谢你的帮助:))

3 个答案:

答案 0 :(得分:0)

您可以使用会话变量:

添加

session_start();

在PHP脚本的最开头。

您的代码可能如下所示:

if(!isset($_SESSION['example'])
{   
    $_SESSION['example'] = some default value;
}

if(isset($_GET['aaa']))
{
  code to be executed;
  $_SESSION['example'] ='a string or codes(calculating)';
}
else
{
  code to be executed;
  use $_SESSION['example'] here
}

$_SESSION['example']可以在任何地方获取值,您也可以在页面刷新后阅读它。

如果您需要更多关于$ _SESSION的示例和说明,可以查看此网站:http://www.php.net/manual/de/reserved.variables.session.php

答案 1 :(得分:0)

在这两种情况下使用$example的最佳方法是在if之前声明它:

$example = '';

if(isset($_GET['aaa']))
{
  code to be executed;
  $example='a string or codes(calculating)';
}
else
{
  //other stuff using $example
  $example = 'foo';
}

阅读this article可能会非常有用。

答案 2 :(得分:0)

在你的情况下尝试 SESSIONS ..

if(isset($_GET['aaa']))
{
  code to be executed;
  $_SESSIONS['example']='a string or codes(calculating)';
}
else
{
  //other stuff using $_SESSIONS['example']
     $_SESSIONS['example'] = 'foo';
}

或者你可能想要在 if block 之前初始化$ _SESSIONS ['example']并使用一些默认值

相关问题