Home > Software design >  Fatal error: Cannot redeclare function when I didn't declare it twice [closed]
Fatal error: Cannot redeclare function when I didn't declare it twice [closed]

Time:09-17

Started working on learning PHP and I don't understand why it is given me an error that says I redeclared a function.

<?php
    class Product {
        var $name;
        var $price;
        var $quantity; 
        var $supplier;

        function __construct($name, $price, $quantity, $supplier){ 
            $this->name = $name;
            $this->price = $price;
            $this->quantity = $quantity;
            $this->supplier = $supplier; 

            function AboveNum(){
                if ($this->price >= 150){
                    return "true";
                }
                return "false";
            }
        }
    }

    $p1 = new Product ("Chippy", 150, 10, "Robinson's");
    $p2 = new Product ("Nova", 180, 10, "Sari-Sari Store");

    echo $p1->AboveNum();

?>

The output should be true;instead it gives me an error saying i redeclared it the function AboveNum() I also noticed that the line my function does not match the line it is on by the console...

CodePudding user response:

You added method inside constructor:

class Product {
    var $name;
    var $price;
    var $quantity; 
    var $supplier;

    function __construct($name, $price, $quantity, $supplier){ 
        $this->name = $name;
        $this->price = $price;
        $this->quantity = $quantity;
        $this->supplier = $supplier; 
    }
    
    function AboveNum(){
        if ($this->price >= 150){
            return "true";
        }
        return "false";
    }
}
  • Related