This may be a dumb questio开发者_如何学编程n but i'll give it a go anyway.
This is for PHP5. Lets say i have two classes Member.class.php
and Forum.class.php
and have a method called returnDate($queryDate)
that can be used in the two classes - for the member class it returns users last seen date and for the forum class it returns last answered. For example, Member: Jonny - last seen **2 mins ago**.
Forum post: last answered **10 mins ago**.
Im assuming it's a bad idea to put this method into the two classes to avoid duplication so im wondering is this where an interface class would come in handy? Or do I do something obvious like create a class for the site to put it in e.g. Website.class.php
. Just trying to further my understanding thanks.
Assuming that the two functions are essentially identical...
My suggestion: Composition > Inheritance.
Create a 'DateHelper' class, and make an instantiation of it a component of each of those classes. That way you've got once place for the code to live (DRY!) and it's clear that there's some shared functionality between the two classes.
You could also make the method static, and call DateHelper::returnDate($x), but I try to minimise use of static functions where I can.
This approach has the advantage of letting you add more date-related functionality, and keeping it in a single place that is comprehensible as being about date-related stuff.
精彩评论