dtml3340 2013-04-30 03:53
浏览 26
已采纳

PHP变量和函数继承

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条回答 默认 最新

  • douwen5924 2013-04-30 03:55
    关注
    $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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试