Griff McGriff
Griff McGriff

Reputation: 3

PHP Variable and Function Inheritance

Im getting the error:

Notice: Undefined variable: avg

Fatal error: Cannot access empty property in /var/www/html/#####/#####/res/calc_food.php on line 37

This is my PHP class:

//Base class for food calculator
abstract class Food {

    protected $avg;                                                 //Average per meal
    protected function equation() {return false;}                      //Equation for total

    //Sets
    public function setAverage($newAvg) {
        $this->$avg = $newAvg;
    }

    //Gets
    public function getAverage() {
        return $this->$avg;
    }

    public function getTotal() {
        $total = $this->equation();

        return $total;
    }
}

//Beef/lamb calculator
class Beef extends Food {

    protected $avg = 0.08037;

    protected function equation() {
        return (($this->$avg*14)-$this->$avg)*_WEEKS;                   //=(1.125-(1.125/14))*52.18;
    }
}

The line it is referring to:

return (($this->$avg*14)-$this->$avg)*_WEEKS;                   //=(1.125-(1.125/14))*52.18;

I'm not sure what the cause of this is. I've tried playing around with scopes. Basically I'm trying to change the base avg value, and the calculating equation for each new food item added, so that food->getTotal() will be different depending on the food child class used.

Upvotes: 0

Views: 82

Answers (4)

vszurma
vszurma

Reputation: 273

Use properties without $:

$this->property 

instead of

$this->$property

correct line:

return (($this->avg*14)-$this->avg)*_WEEKS;    

Upvotes: 0

bbldzr
bbldzr

Reputation: 151

You should try this:

$this->avg // no $avg

Upvotes: 0

Tasos Bitsios
Tasos Bitsios

Reputation: 2789

$this->$avg 

...will first evaluate $avg to whatever it may be (in this case, nothing), and then look that up in the $this object. You want:

$this->avg

which will look up the "avg" property of the $this object.

Upvotes: 1

zerkms
zerkms

Reputation: 254886

You must access properties without $:

$this->avg

Upvotes: 1

Related Questions