c_pattle Posted August 1, 2011 Share Posted August 1, 2011 I have just begun to play around with inheritance when using OOP and have come across a problem. I have two classes, one called "firstClass" that is the parent class and another that is called "secondClass" that is the child class. I know that in the child class I can override the methods in the parent class but do you have to override them completely or can you just override certain bits of them? For example say in I have this method in the firstClass. function doSomething() { $firstline = "<p>Hello</p>"; $secondlne = "<p>World</p>"; $thirdline = "<p>!</p>" } Then what do I do if I only want to override the second line of this function in the child class "secondClass"? Is it best to just override everything or are there recommended design patterns for this sort of thing? Thanks for any help. Quote Link to comment https://forums.phpfreaks.com/topic/243507-oop-inheritance-help/ Share on other sites More sharing options...
AyKay47 Posted August 1, 2011 Share Posted August 1, 2011 its really up to you as to what you want to change and what you don't want to change.. function doSomethingElse extends doSomething() { piblic $firstline = "<p>Hello</p>"; $second_line = parent::secondline} Quote Link to comment https://forums.phpfreaks.com/topic/243507-oop-inheritance-help/#findComment-1250327 Share on other sites More sharing options...
gizmola Posted August 1, 2011 Share Posted August 1, 2011 In your example, then the way to do that would be in firstclass to have doSomething call the parent method first. function doSomething() { parent::doSomething(); $secondline = " World"; } Quote Link to comment https://forums.phpfreaks.com/topic/243507-oop-inheritance-help/#findComment-1250329 Share on other sites More sharing options...
c_pattle Posted August 1, 2011 Author Share Posted August 1, 2011 Awesome thanks guys. Two good solutions. Quote Link to comment https://forums.phpfreaks.com/topic/243507-oop-inheritance-help/#findComment-1250439 Share on other sites More sharing options...
ignace Posted August 2, 2011 Share Posted August 2, 2011 If you could give us an example that we can work with instead of firstClass and secondClass I'm sure we can come up with even better approaches. Template Method for example is a design pattern specifically targeted at this. Quote Link to comment https://forums.phpfreaks.com/topic/243507-oop-inheritance-help/#findComment-1250553 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.