0

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

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

4

1 回答 1

0
<?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
?>

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

于 2010-04-03T13:40:04.953 回答