Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Object-Oriented PHP Basics (Retired) Inheritance, Interfaces, and Exceptions Final Challenge

Keeping it DRY

While I managed to finish the Challenge, I feel like I wrote dirty code ( http://pastebin.com/T5Bjfu6D )... I tried to use the parent::getInfo() trick to avoid rewriting the original method ( http://pastebin.com/m8jCb6e6 ) but I got an Undefined error: output error, that I just simply don't understand.

Did anyone else succeed using the parent::getInfo() way and if so, would you mind sharing your code ?

2 Answers

Hello,

Your question about DRY can be answered yes and no. The example in the lesson can be misleading but in that example what you are basically doing is overriding the parent's method. Most of the time you are going to use the same named method in the child class but maybe do something a little bit different. In that case you are not duplicating your code, you are modifying the method from the parent class and making it better (overriding). Now in the example provided by Muhammad, If you just want to return all of the properties in both classes in a human-readable phrase and just want to add additional words to the return then you can just recall the parent method and append what you want. Normally if you want to add or modify code inside of the method blocks, you will have to re-declare the method again in the child class since child classes can inherit from their parents, but parents cannot inherit from their children.

By the way, your second snippet of code is throwing out an error because you are just calling the parent method and not assigning it to anything. Since the parent method getInfo() returns a value, you must either echo it out, return the value from the method (if it's within a function), or assign it to a variable to use later. If you don't, you are returning something from the method into nothing which is throwing you the error. Hope this helps.

Cheers!

Nicely explained shawn... I really think that they should change that example a little as it tripped me this morning as well . cheers :)

May be following will help. cheers

   public function getInfo() {
        return parent::getInfo().' Child class';        
     }

http://stackoverflow.com/questions/12934744/calling-a-child-method-from-the-parent-class-in-php for further info. cheers