在两种条件下使用变量


Work with variables in two conditions

我在处理第二个条件中一个条件中的变量时遇到了问题。我有这样的东西:

<form name="exampleForm" method="post">
...
<input type="submit" name="firstSubmit" value="Send">
<input type="submit" name="secondSubmit" value="Show">
</form>
<?php
if(isset($_POST['firstSubmit'])) {
 function a() {
  $a = 5;
  $b = 6;
  $c = $a + $b;
  echo "The result is $c";
  return $c;
 }
 $functionOutput = a();
}
if(isset($_POST['secondSubmit'])) {
 echo $functionOutput;
}
?>

当我需要从第一个条件处理变量$functionOutput时,我总是收到一条错误消息(未定义的变量)。我该如何解决这个问题?

我不确定你到底想做什么,但当你按下第二个按钮时,变量$functionOutput没有被定义为第一个条件是false,所以整个部分都被跳过了。

请注意,一旦脚本结束,变量就会丢失。您可以查看会话并使用会话变量来解决这个问题,但这在一定程度上取决于您想要做什么。

要使用会话,您必须将整个php块移动到开始输出html的位置,然后执行以下操作:

<?php
session_start();
if(isset($_POST['firstSubmit'])) {
 function a() {
  $a = 5;
  $b = 6;
  $c = $a + $b;
  return $c;
 }
 $_SESSION['output'] = a();
}

// start html output
?>
<doctype .....
<html ....
// and where you want to echo
if(isset($_POST['firstSubmit'])) {
  echo "The result is {$_SESSION['output']}";
}
if(isset($_POST['secondSubmit'])) {
 echo $_SESSION['output'];
}
<?php
$functionOutput = "";
if(isset($_POST['firstSubmit'])) {
 function a() {
  $a = 5;
  $b = 6;
  $c = $a + $b;
  echo "The result is $c";
  return $c;
 }
 $functionOutput = a();
}
if(isset($_POST['secondSubmit'])) {
 echo $functionOutput;
}
?>

应该修复它。发生这种情况是因为您在第一个IF语句中声明$functionOutput。

因为调用if(isset($_POST['secondSubmit']))$functionOutput未初始化

<?php
if(isset($_POST['firstSubmit'])) {
 function a() {
  $a = 5;
  $b = 6;
  $c = $a + $b;
  echo "The result is $c";
  return $c;
 }
 $functionOutput = a();
}
$functionOutput='12';//intialize
if(isset($_POST['secondSubmit'])) {
 echo $functionOutput;
}
?> 
         **OR**
<?php
if(isset($_POST['firstSubmit'])) {
 function a() {
  $a = 5;
  $b = 6;
  $c = $a + $b;
  echo "The result is $c";
  return $c;
 }
 $functionOutput = a();
}
if(isset($_POST['secondSubmit'])) {
 function a() {
  $a = 5;
  $b = 6;
  $c = $a - $b;
  echo "The result is $c";
  return $c;
 }
 $functionOutput = a();
 echo $functionOutput;
}
?>