I want to add additional stuff to the parent class. I can't modify the parent class because all modifications will be erased when the software is upgraded. So I want to extend the class. Can I just add this in the child class without repeating parent functions?
class parent
{
public function __construct()
{
// lots of logic to hook up following functions with main software
}
// lots of parent functions
}
class child extends parent
{
function __construct()
{
// Is this going to share parent's logic and hook up with those actions?
// Or, should I repeat those logics?
parent::__construct();
// add child addicional logic
}
// child functions
// should I repeat parent's functions? I need the parent take child along all the jobs.
}
Yes, that is the correct way to do it.
class parent
{
public function __construct()
{
// lots of logic to hook up following functions with main software
}
// lots of parent functions
protected function exampleParentFunction()
{
//do lots of cool stuff
}
}
class child extends parent
{
function __construct()
{
// This will run the parent's constructor
parent::__construct();
// add child additional logic
}
// child functions
public function exampleChildFunction();
{
$result = $this->exampleParentFunction();
//Make result even cooler :)
}
//or you can override the parent methods by declaring a method with the same name
protected function exampleParentFunction()
{
//use the parent function
$result = parent::exampleParentFunction();
//Make result even cooler :)
}
}
Going by your recent questions you really need to read a book on PHP OOP. Start with the manual http://www.php.net/oop
Yes, as vascowhite said, that is the correct way to do.
As for repeating parent functions, you don't have to, unless you want to add additional logic to those functions too. e.g.
class foo {
protected $j;
public function __construct() {
$this->j = 0;
}
public function add($x) {
$this->j += $x;
}
public function getJ() {
return $this->j;
}
}
class bar extends foo {
protected $i;
public function __construct() {
$this->i = 0;
parent::__construct();
}
public function add($x) {
$this->i += $x;
parent::add($x);
}
public function getI() {
return $this->i;
}
// no need to redo the getJ(), as that is already defined.
}