获取要在PHP中输出的类的结果


Getting the result of a class to output in PHP

我正在尝试使用一个类来计算数字并将其输出到屏幕上。用户输入数字,然后计算并在表格上方的屏幕上输出。

我使用post方法将表单结果发布到我所在的页面上,然后尝试在Fibonacci类中使用它。

数字需要遍历类,然后根据用户输入的内容输出结果。我认为大部分内容都是正确的,但有一些东西让我无法完全理解。

提前谢谢。

这是我的代码:

<?php
class Fibonacci {
    //method to check numbers
function checkFibo(){
        $n1 = $_POST["n1"];
        $n2 = $_POST["n2"];
        $output = "";
        if($n1!=0 && $n2!=0){
            if($n2<$n1){
                echo "Your second number must be greater than the first. Try again";        
                $output="Your second number must be greater than the first. Try again";
            }
           else if($n1<0 || $n2<0){
                echo "Please enter only positive numbers";
                $output = "Please enter positive numbers";
            }
            else if (!(is_numeric($n1)) || !(is_numeric($n2))){
                echo "Please only enter positive numbers";
                $output="";
            }
            else{
                echo "The result of your request is shown below.";
                $output=$fibo->getFibo($n1,$n2);
                echo $output;
            }
        }
        else{
                echo "<p>Please enter good values</p>";
        }

    }
     // Method to calculate fibonacci
    function getFibo($n1 = 0, $n2 = 0) {
        $max=$n2 * 100;
        $output = "";
        while($z<=$max){
                 $z = $n1 + $n2;
                $output.=($z."<br />");
                $n1 = $n2;
                $n2 = $z;
        }
        return $output;
    }

} // End of Fibonacci class.

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>Fibonacci</title>
</head>
<body>
<?php 
if (!empty($_POST)){
    $fib = new Fibonacci();
    echo "hello";
    echo $output;
} 

echo "<h2> Fibonacci Example </h2>";
echo "<form method='"post'" action='"index.php'">";
echo "<table>";
echo "<tr>";
echo "<td>First Number</td>";
echo "<td><input type='"text'" name='"n1'"/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Second Number</td>";
echo "<td><input type='"text'" name='"n2'"/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>&nbsp;</td>";
echo "<td><input type='"submit'" value='"go!'"/></td>";
echo "</table>";
echo "</form>";


?>
</body>
</html>

我想我看到了这个问题。

$output=$fibo->getFibo($n1,$n2);

我认为应该是:

$output = $this->getFibo($n1,$n2);

要进行测试,请在getFibo函数中放入一条echo语句,以查看是否打印出任何内容。您还可以运行$output的var_dump,看看它会返回什么。

还有一行:

$fib = new Fibonacci();
echo "hello";
echo $output;

应为:

$fib = new Fibonacci();
echo "hello";
$fib->getFibo();

不过你还有一个问题。它正在创建一个无限循环。您需要确保$z最终总是大于$max,或者设置一个最大循环计数并打破一个已达到最大值的循环计数。

查看您的代码,变量$output可能是个问题。

$output.=($z."<br />");

您可以对$output进行串联,而不需要实际声明或设置它的开头。

因此,也许可以尝试在while循环之前制作$output = ""