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.
$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.
You must access properties without $
:
$this->avg
You should try this:
$this->avg // no $avg
Use properties without $:
$this->property
instead of
$this->$property
correct line:
return (($this->avg*14)-$this->avg)*_WEEKS;