** 第一个 PHP 类,可能需要更多解释才能理解。
对于我的PHP类,我必须创建一个计算斐波那契的类。所以这是我的代码,我有一个带有两个函数的类,它们为斐波那契示例传递了 2 个数字。我有一个收集数字并传递给php文件(名为fibonacciClass.php)的表单:
它还在结束时调用类启动。
<form method = "post" action = "">
<center>
<table>
<tr>
<th>Fibonacci Class</th>
</tr>
<tr>
<td>First Number:</td>
<td><input type="text" name="num1" /></td>
</tr>
<tr>
<td>Second Number:</td>
<td><input type="text" name="num2"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Calculate!" /></td>
</tr>
</table>
</center>
</form>
<?php
require_once('fibonacci.php');
if($_POST['submit']){
$fibo = new fibonacci();
$fibo ->checkFibo();
$fibo ->getFibo();
}
?>
其次,我有包含我的函数的类文件,这是我得到致命错误的地方。它的一行:$output=$checkFibo->getFibo($n 1,$n 2);
<?php
class fibonacci {
//method to check numbers
function checkFibo($n1=0,$n2=0){
$n1 = $_POST['num1'];
$n2 = $_POST['num2'];
if($n1!=0 && $n2!=0){
if($n2<$n1){
echo "<p>Your second number must be greater than the first. Try again</p>";
$output="";
}
else if($n1<0 || $n2<0){
echo "<p>Please enter only positive numbers</p>";
}
else if (!(is_numeric($n1)) || !(is_numeric($n2))){
echo "<p>Please only enter numbers</p>";
$output="";
}
else{
echo "<p>The result of your request is shown below.</p>";
$output=$checkFibo->getFibo($n1,$n2);
}
}
else{
echo "<p>Please enter a valid value(s) above (non zero)</p>";
$output="";
}
return $output;
}
// Method to calculate fibonacci
function getFibo($n1 = 0, $n2 = 0) {
$n1 = $_POST['num1'];
$n2 = $_POST['num2'];
$max=$n2 * 100;
while($z<=$max){
$z = $n1 + $n2;
$output.=($z."<br />");
$n1 = $n2;
$n2 = $z;
}
return $output;
}
}
?>
我在提交时收到的确切错误:
致命错误:在非对象上调用成员函数 getFibo()。
对于类,成员函数有一个作用域。若要访问需要使用的类成员函数$this
$output = $this->getFibo($n1,$n2);