0

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.

4 Answers 4

1
$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.

Sign up to request clarification or add additional context in comments.

1 Comment

This was the problem, thank you. Is it still correct to use $this->$avg in the parent class functions?
1

You must access properties without $:

$this->avg

Comments

0

You should try this:

$this->avg // no $avg

Comments

0

Use properties without $:

$this->property 

instead of

$this->$property

correct line:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.