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
?
class Brother extends Mother{
protected $totalRows;
public function __construct($totalRows){
$this->totalRows = $totalRows;
}
}
Working ?
init Brother class before Sister class. Define totalRows inside Mother class and you should be fine. For example define totalRows array and use it like that:
class Mother{
public $totalRows = array();
public function __construct($itemPerPage){
$this->itemPerPage = $itemPerPage;
}
}
class Brother extends Mother{
public function __construct($totalRows){
$this->totalRows['brother'] = $totalRows;
}
}
But remember, if You dont init Mother class, use parent::__construct inside your Brother construction. Otherwise Mother constructor will be overrided