0

我在处理第二种情况下的一种情况下的变量时遇到问题。我有类似的东西:

<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第一个条件的变量时,我总是会收到一条错误消息(未定义的变量)。我该如何解决这个问题?

4

3 回答 3

2

我不确定您到底要做什么,但是当您按下第二个按钮时,变量$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'];
}
于 2012-08-31T14:48:47.260 回答
1
<?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。

于 2012-08-31T14:48:30.020 回答
1

As$functionOutput在您调用时未初始化if(isset($_POST['secondSubmit']))

<?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;
}
?> 
于 2012-08-31T14:52:13.600 回答