note 79432 deleted from language.oop.constructor by danbrown

From: 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.

« previous php.notes (#162520) next »