我怎样才能实现这种关系(继承、组合、其他)?
我想为应用程序建立一个基础课程,其中两个是个人和学生。一个人可能是学生,也可能不是,但学生始终是一个人。学生“是一个”人的事实促使我尝试继承,但在我有一个返回人的实例的 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();
}
这显然行不通,但是达到这种效果的最佳方法是什么?在我看来,作文听起来不对劲,因为一个人没有“一个”学生。我不一定要寻找解决方案,而可能只是要搜索的术语或短语。由于我不太确定如何称呼我正在尝试做的事情,所以我运气不太好。谢谢你!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会选择一种方式并坚持下去。只是展示各种想法和技术。
I would choose one way and stick to it. Just deomonstrating various ideas and techniques.