我在第二个条件中处理来自一个条件的变量的问题。我有类似的东西:
<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
时,我总是会得到一条错误消息(未定义的变量)。我怎么能解决这个问题?
答案 0 :(得分:2)
我不确定你要做什么,但是当你按下第二个按钮时,变量$functionOutput
没有定义为第一个条件是false
,所以跳过了整个部分
请注意,一旦脚本结束,变量就会丢失。您可以查看sessions并使用会话变量来解决这个问题,但这取决于您想要做什么。
要使用会话,您必须将整个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'];
}
答案 1 :(得分: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。
答案 2 :(得分:1)
当您致电$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;
}
?>