OOP in PHP not the same as Java
We all know that PHP5 has a lot more OOP features than PHP4, and we all know that it is not a real OOP language. There are a lot of things in PHP5 that won’t work like Java (obviously). With that said, I just want to point out one feature that I noticed while playing with PHP5 classes.
In Java, when you extend a class, it will run the parent’s class constructor first, then it will invoke the subclass’s constructor. Unfortunately in PHP5, when you extend a class, it will NOT invoke the parent class. You will have to manually invoke it yourself using the ‘parent::’ construct. Here’s some code (syntax may be wrong, excuse me, but you get the point):
class Hello
{
public function __construct()
{
echo "Hello";
}
}
class World extends Hello
{
public function __construct()
{
parent::_construct(); //<-- must do that in order for the output to be "Hello World!";
echo " World!";
}
}
$test = new World();
?>
Output above would be..
Hello World!
If you didn’t add the parent::__construct(), output would be..
World!