note 79432 deleted from language.oop.constructor by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 18:56:59 +0000 |
| Subject: | note 79432 deleted from language.oop.constructor by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162520@lists.php.net to get a copy of this message | ||
Note Submitter: alexey at gmail dot com
----
Being a mostly C/C++ developer, I was suprised how PHP handles inheritance - quite differently.
Imagine a child class that inherits from a parent. Typically, a childâs constructor invokes
parentâs one according to the hierarchy. The interesting observation is that if parent invokes
a method, that call goes to the child under construction!
Here is an example code:
class test_parent {
function test_parent() {
$this->func();
}
function func() {
echo âfunc_parent\nâ;
}
}
class test_child extends test_parent {
function test_child() {
test_parent::test_parent();
}
function func() {
echo âfunc_child\nâ;
}
}
$tmp = new test_child();
?>
The output is func_child which is the result of test_parent invoking func(). Here is an equivalent
C++ code.
#include
class test_parent {
public:
test_parent() {
this->func();
}
void func() {
printf(âfunc_parent\nâ);
}
};
class test_child: test_parent {
public:
test_child() {
}
void func() {
printf(âfunc_child\nâ);
}
};
int main() {
class test_child *t;
t=new test_child();
return 0;
}
It prints out func_parent as the child is not available at the time when parent initializes itself.