PHP变量和函数继承

时间:2013-04-30 03:53:10

标签: php inheritance scope

我得到错误:

Notice: Undefined variable: avg

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

这是我的PHP课程:

//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;
    }
}

它指的是:

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

我不确定这是什么原因。我试过玩范围。基本上我正在尝试更改基本平均值,并添加每个新食品的计算公式,以便食品 - > getTotal()将根据所使用的食品子类别而有所不同。

4 个答案:

答案 0 :(得分:1)

您必须访问不带 $的商品

$this->avg

答案 1 :(得分:1)

$this->$avg 

...将首先评估$ avg到它可能是什么(在这种情况下,什么都没有),然后在$ this对象中查找 。 你想要:

$this->avg

将查找$ this对象的“avg”属性。

答案 2 :(得分:0)

你应该试试这个:

$this->avg // no $avg

答案 3 :(得分:0)

使用没有$:

的属性
$this->property 

而不是

$this->$property

正确的行:

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