valdemark Posted September 24, 2007 Share Posted September 24, 2007 Hey there! First, please excuse me if someone have already asked the same question or if the problem is described in the tutorials/manual pages - I wasn't able to really find the answer anywhere and that's why I'm posting it here. It is rather a simple OO related question. I have the following code: <?php class one { function one(){ echo "one<br>"; } } class two extends one { function two(){ echo "two<br>"; } } $obj = new two(); ?> Since I'm used with Java, I somehow assumed that this would produce: "one, two" because class Two extends One and the constructor of One should be called. This however is not the case and instead of the expected result, just "two" is displayed. The question is, how can I ensure that the constructor of the parent class has been executed? Again, sorry if the question is stupid or has been already answered Quote Link to comment https://forums.phpfreaks.com/topic/70449-oo-inheritance/ Share on other sites More sharing options...
jitesh Posted September 24, 2007 Share Posted September 24, 2007 Yes in java when you create a instance for a child class then the constructor for parent will be call automatically. But in PHP is not like that . it is calling the constructor for only requested class. you can try this. <?php class one { function one(){ echo "one<br>"; } } class two extends one { function two(){ $this->one(); echo "two<br>"; } } $obj = new two(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/70449-oo-inheritance/#findComment-353939 Share on other sites More sharing options...
rarebit Posted September 24, 2007 Share Posted September 24, 2007 mmm, I would of expected the same, but this is how it happens! Can see how it might have it's use's though! Quote Link to comment https://forums.phpfreaks.com/topic/70449-oo-inheritance/#findComment-353941 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.