How can I achieve this kind of relationship (inheritance, composition, something else)?
Posted
by Tim
on Stack Overflow
See other posts from Stack Overflow
or by Tim
Published on 2010-04-03T13:20:58Z
Indexed on
2010/04/03
13:23 UTC
Read the original article
Hit count: 171
I would like to set up a foundation of classes for an application, two of which are person and student. A person may or may not be a student and a student is always a person. The fact that a student “is a” person led me to try inheritance, but I can't see how to make it work in the case where I have a DAO that returns an instance of person and I then want to determine if that person is a student and call student related methods for it.
class Person {
private $_firstName;
public function isStudent() {
// figure out if this person is a student
return true; // (or false)
}
}
class Student extends Person {
private $_gpa;
public function getGpa() {
// do something to retrieve this student's gpa
return 4.0; // (or whatever it is)
}
}
class SomeDaoThatReturnsPersonInstances {
public function find() {
return new Person();
}
}
$myPerson = SomeDaoThatReturnsPersonInstances::find();
if($myPerson->isStudent()) {
echo 'My person\'s GPA is: ', $myPerson->getGpa();
}
This obviously doesn't work, but what is the best way to achieve this effect? Composition doesn't sond right in my mind because a person does not “have a” student. I'm not looking for a solution necessarily but maybe just a term or phrase to search for. Since I'm not really sure what to call what I'm trying to do, I haven't had much luck. Thank you!
© Stack Overflow or respective owner