Julia
Julia

Reputation: 57

Fatal error: Call to a member function, not sure what to call variable

** first php class, may need more explanation to understand.

For my PHP class I have to create a class that will calculate Fibonacci. So here is my code, I have a class with two functions that are passed 2 numbers for a fibonacci example. I have one form which collects numbers and passes to php file (named fibonacciClass.php):

It also calls the class initiation at the end.

<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>&nbsp;</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();

    }
?>

Second I have my class file which contains my functions, this is where I am getting the fatal error. Its the one line: $output=$checkFibo->getFibo($n1,$n2);

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

  }


?>

Exact error I receive upon submit:

Fatal error: Call to a member function getFibo() on a non-object.

Upvotes: 3

Views: 121

Answers (1)

rockerBOO
rockerBOO

Reputation: 3030

With classes, there is a scope to the member functions. To access the class member functions you'll want to use $this

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

Upvotes: 3

Related Questions