我想建立一個應用程序類的基礎,其中兩個是人和學生。一個人可能是也可能不是學生,學生永遠是一個人。事實上,一個學生「是一個」的人導致我嘗試繼承,但我不知道如何使它在我有一個返回人的實例的DAO的情況下工作,然後我想確定該人是否是一名學生,併爲其調用與學生相關的方法。我該如何實現這種關係(繼承,構圖,其他)?
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();
}
這顯然不起作用,但達到這種效果的最佳方法是什麼?因爲一個人沒有「擁有」一個學生,所以作文在我的腦海中並不正確。我不是在尋找一個解決方案,但可能只是一個術語或短語來搜索。由於我不確定要調用什麼,所以我沒有太多的運氣。謝謝!
你在學生中重寫了'isStudent()',對吧? – kennytm 2010-04-03 13:33:19
我可以,是的。在Student類中,isStudent()將始終爲真。如果我有一個基類Person的實例,isStudent()可能會或可能不會成立。 – Tim 2010-04-03 17:03:17