note 79432 added to language.oop.constructor
| From: | alexey at gmail dot com | Date: | Tue, 27 Nov 2007 13:15:27 +0000 |
| Subject: | note 79432 added to language.oop.constructor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132591@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 69.147.83.197
Probable Submitter: 82.208.97.93
----
Manual Page -- http://www.php.net/manual/en/language.oop.constructor.php
Edit -- https://master.php.net/note/edit/79432
Del: integrated -- https://master.php.net/note/delete/79432/integrated
Del: useless -- https://master.php.net/note/delete/79432/useless
Del: bad code -- https://master.php.net/note/delete/79432/bad+code
Del: spam -- https://master.php.net/note/delete/79432/spam
Del: non-english -- https://master.php.net/note/delete/79432/non-english
Del: in docs -- https://master.php.net/note/delete/79432/in+docs
Del: other reasons-- https://master.php.net/note/delete/79432
Reject -- https://master.php.net/note/reject/79432
Search -- https://master.php.net/manage/user-notes.php