Question

i've wrote this code,

<?php
class fizzbuzz{
    function mod3($angka)
    {
        $a = $angka % 3;
        if($a==0) return true;
        else return false;
    }
    function mod5($angka)
    {
        $b = $angka % 5;
        if($b==0) return true;
        else return false;
    }
    function index(){
        for ($i=1; $i < 101; $i++) { 
            if(mod3($i) == true && mod5($i) == true){
                echo "fizzbuzz, ";
            }else if(mod3($i) == true){
                echo "fizz, ";
            }else if(mod5($i) == true){
                echo "buzz, ";
            }else echo $i.", ";
        }
    }
}
$show = new fizzbuzz;
$show->index();
?>

and then it came up with this error

Fatal error: Call to undefined function mod3() in C:\xampp\htdocs\tes-bimasakti\fizzbuzz.php on line 19

please help me with this error..

Était-ce utile?

La solution

You forgot $this->:

    if($this->mod3($i) == true && $this->mod5($i) == true){
       ^^^^^^^--- here            ^^^^^^^---here

without $this->, php is looking for a top-level global function. It will NOT look for a method in your object.

Autres conseils

use this keyword

function index(){
    for ($i=1; $i < 101; $i++) { 
        if($this->mod3($i) == true && $this->mod5($i) == true){
            echo "fizzbuzz, ";
        }else if($this->mod3($i) == true){
            echo "fizz, ";
        }else if($this->mod5($i) == true){
            echo "buzz, ";
        }else echo $i.", ";
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top