[Solved] Inheriting parent methods in OO PHP
Posted: Thu Feb 22, 2007 9:57 am
How to inherit parent method in PHP?
Giving the following class for example (from http://swik.net/PHP/Object+Oriented+PHP),
I want that in the HelloWorld2 class, inherit the parent HelloWorld methods. E.g., in construction, call parent construction first then add '\nand more' to $word. In print(), having called parent print() method, echo another '\ndone'.
So the final output will be:
hello world
and more
done
How could I do that?
thanks a lot
Got partial answer from
http://www.sitepoint.com/article/object-oriented-php/8
[...]
Please show me how to do the cascading constructors.
I've updated your code to show how to call the parent constructor & expand on the $word variable. print() is a built-in PHP function, so I renamed the function to dump() (untested, but I'm not sure how happy PHP would be to have an object function be the same name as a built-in function. At the very least you should stay away from it in case you type print('blah') when you were really meaning $this->print('blah')).
Giving the following class for example (from http://swik.net/PHP/Object+Oriented+PHP),
Code: Select all
Class HelloWorld
{
public $word;
public function __construct($word)
{
$this->word = $word;
}
public function print()
{
echo $this->word;
}
}
class HelloWorld2 extends HelloWorld
{
}
$hello = new HelloWorld2('hello world');
$hello->print();So the final output will be:
hello world
and more
done
How could I do that?
thanks a lot
Got partial answer from
http://www.sitepoint.com/article/object-oriented-php/8
[...]
Please show me how to do the cascading constructors.
Code: Select all
Class HelloWorld
{
public $word;
public function __construct($word)
{
$this->word = $word;
}
public function dump()
{
echo $this->word;
}
}
class HelloWorld2 extends HelloWorld
{
public function __construct($word)
{
parent::__constructor($word);
$this->word .= "\nand";
}
public function dump()
{
parent::dump();
echo '\ndone';
}
}