2012-08-31 56 views
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工作,我总是得到一个错误信息(未定义的变量)。我如何解决这个问题?

回答

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。

+0

谢谢,但这种解决方案并不好。 – Mato

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']; 
} 
+0

感谢您的回答。我还有一个问题。安全使用会话吗? – Mato

+0

@Mato当然,所有的信息都存储在服务器端。还有一点,你可以添加会话和表单变量来避免会话劫持,但是你必须查看更多细节。 – jeroen

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; 
} 
?>