duangou2046 2015-09-01 08:02
浏览 94

如何在面向对象的PHP中将变量从扩展类传递到另一个

I have been trying to change my functions that heavily use global variables into classes. I got into a problem of accessing the variable $totalRows in class Sister, which is a total row count fetched from mysql and passed into the extended class Brother.

Just a pseudo code to get the point across. The real situation is more complicated and prevents me from putting all these into one big class:

class Mother{

  public function __construct($itemPerPage){

     $this->itemPerPage = $itemPerPage;
  }
}

class Brother extends Mother{

    public function __construct($totalRows){

       $this->totalRows = $totalRows;

    }
}

class Sister extends Mother{

    public function renderPager(){

       $totalRows = $this->totalRows;

       $itemPerPage = $this->itemPerPage;

       $totalPages = ceil($totalRows/$itemPerPage);

    }
}

The $totalRows can't be read in Sister because it is not in the main class Mother. Should I just simply pass the $totalRows again in a __construct function in Sister? Is there another way to pass $totalRows from Brother to Sister?

  • 写回答

2条回答 默认 最新

  • douliu1092 2015-09-01 08:10
    关注
    class Brother extends Mother{
      protected $totalRows;
        public function __construct($totalRows){
    
           $this->totalRows = $totalRows;
    
        }
    }
    

    Working ?

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?