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

时间:2015-09-01 08:02:34

标签: php oop

我一直在尝试将大量使用全局变量的函数更改为类。我遇到了访问类$totalRows中的变量Sister的问题,这是从mysql获取并传递到扩展类Brother的总行数。

只是一个伪代码来解决问题。真实情况更加复杂,使我无法将所有这些变成一个大班:

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);

    }
}

$totalRows无法在Sister中阅读,因为它不在主要课程Mother中。我应该只是在$totalRows的__construct函数中再次传递Sister吗?还有另一种方法可以将$totalRowsBrother传递到Sister吗?

2 个答案:

答案 0 :(得分:0)

class Brother extends Mother{
  protected $totalRows;
    public function __construct($totalRows){

       $this->totalRows = $totalRows;

    }
}

工作?

答案 1 :(得分:0)

在姐姐上课之前初学兄弟班。在Mother类中定义totalRows,你应该没问题。例如,定义totalRows数组并使用它:

class Mother{
    public $totalRows = array();
  public function __construct($itemPerPage){

     $this->itemPerPage = $itemPerPage;
  }
}

class Brother extends Mother{

    public function __construct($totalRows){

       $this->totalRows['brother'] = $totalRows;

    }
}

但是请记住,如果你不启动Mother类,请在你的Brother结构中使用parent :: __ construct。否则母亲的构造函数将被覆盖

相关问题