note 79432 added to language.oop.constructor

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

« previous php.notes (#132591) next »