我该如何实现这种关系(继承,构图,其他)?

问题描述:

我想建立一个应用程序类的基础,其中两个是人和学生。一个人可能是也可能不是学生,学生永远是一个人。事实上,一个学生“是一个”的人导致我尝试继承,但我不知道如何使它在我有一个返回人的实例的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(); 
} 

这显然不起作用,但达到这种效果的最佳方法是什么?因为一个人没有“拥有”一个学生,所以作文在我的脑海中并不正确。我不是在寻找一个解决方案,但可能只是一个术语或短语来搜索。由于我不确定要调用什么,所以我没有太多的运气。谢谢!

+0

你在学生中重写了'isStudent()',对吧? – kennytm 2010-04-03 13:33:19

+0

我可以,是的。在Student类中,isStudent()将始终为真。如果我有一个基类Person的实例,isStudent()可能会或可能不会成立。 – Tim 2010-04-03 17:03:17

<?php 
class Person { 
    #Can check to see if a person is a student outside the class with use of the variable 
    #if ($Person->isStudentVar) {} 
    #Or with the function 
    #if ($Person->isStdentFunc()) {} 

    public $isStudentVar = FALSE; 

    public function isStudentFunc() { 
     return FALSE; 
    } 
} 

class Student extends Person { 
    #This class overrides the default settings set by the Person Class. 
    #Also makes use of a private variable that can not be read/modified outside the class 

    private $isStudentVar = TRUE; 

    public function isStudentFunc() { 
     return $this->isStudentVar; 
    } 

    public function mymethod() { 
     #This method extends the functionality of Student 
    } 
} 

$myPerson1 = new Person; 
if($myPerson1->isStudentVar) { echo "Is a Student"; } else { echo "Is not a Student"; } 
#Output: Is not a Student 

$myPerson2 = new Student; 
if($myPerson2->isStudentFunc()) { echo "Is a Student"; } else { echo "Is not a Student"; } 
#Output: Is a Student 
?> 

我会选择一种方式并坚持下去。只是去了各种想法和技巧。

+0

感谢您的回复。基础Person类中的isStudentFunc()不会总是返回false。如果它返回true,我希望能够做到这样的事情: $ myPerson1 = new Person(); if($ myPerson1-> isStudentFunc()){$ myPerson1-> mymethod(); } – Tim 2010-04-03 17:02:28