我有下面的php测验代码。
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(($_POST['q_1'] == '') || ($_POST['q_2'] == '') || ($_POST['q_3'] == '') || ($_POST['q_4'] == '') || ($_POST['q_5'] == '')) {
$nameError = 'Please choose an option';
$hasError = true;
}
else {
for ($i=1; $i<=$types; $i+=1)
{
$nowval[$i] = 0;
}
for ($i=1; $i<=$questions; $i+=1)
{
$qvar = "q_$i";
//echo $qvar;
tally($_POST[$qvar]);// LINE THAT CAUSES ERROR
}
$dominant = 1;
$domval = $nowval[1];
for ($i=2; $i<=$types; $i+=1)
{
if ($domval < $nowval[$i])
{
$dominant = $i;
$domval = $nowval[$i];
}
}
function tally ($question) // TALLY FUNCTION
{
global $nowval;
$nowval[$question]++;
}
if (is_file("$quiz.rsl"))
{
$fp = fopen("$quiz.rsl", 'r');
$line = fgets($fp, 1024);
fclose($fp);
$people = explode("|", $line);
$people[$dominant-1] += 1;
$timestaken = 0;
foreach($people as $tally)
{
settype($tally, 'integer');
$timestaken += $tally;
}
$fp = fopen("$quiz.rsl", 'w');
for($i=0; $i<$types; $i++)
{
fwrite($fp, $people[$i]."|");
}
fclose($fp);
}
else
{
for($i=0; $i<$types; $i++)
{
$people[] = 0;
}
$people[$dominant-1] += 1;
$timestaken = 1;
$fp = fopen("$quiz.rsl", 'w');
for($i=0; $i<$types; $i++)
{
fwrite($fp, $people[$i]."|");
}
fclose($fp);
}
$percentage = ($people[$dominant-1] / $timestaken) * 100;
$dec=2;
$format="%.$dec" . "f";
$number=sprintf($format,$percentage);
$percentage=strtok($number,".");
$dc=strtok(".");
if ($dec!=0)
{
$percentage = "$percentage" . ".$dc";
}
$emailSent = true;
}//else
}//main if当我POST表单数据到一个不同的文件时,如果上面的代码写在一个单独的文件中,一切都很好。
但是,当我将表单数据POST到页面本身时,我会得到
Fatal error: Call to undefined function tally()我不理解这个问题的根本原因。
当我尝试使用
$this->tally($_POST[$qvar]);我得到了以下错误。
Fatal error: Using $this when not in object context发布于 2014-04-23 21:33:45
发生这种情况是因为您在尝试调用函数后声明了该函数:
tally($_POST[$qvar]);// LINE THAT CAUSES ERROR
function tally ($question) // TALLY FUNCTION DECLARATION COMES LATER我会把它放在if(isset($_POST['submit'])) {之前,或者作为里面的第一件事。
if (!function_exists('tally')) {
function tally ($question) // TALLY FUNCTION
{
global $nowval;
$nowval[$question]++;
}
}$this->tally不起作用,因为它不是一个对象,你只是在拒绝一个函数。
发布于 2014-04-23 21:31:56
您是在调用函数之后定义它的。此外,您只能有条件地定义它(即在if..else中)。首先定义您的函数,然后编写使用它们的代码。
https://stackoverflow.com/questions/23245854
复制相似问题