我怎样才能实现这种关系(继承,组合,其他)?

时间:2010-04-03 13:20:58

标签: php design-patterns inheritance class composition

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

这显然不起作用,但实现这种效果的最佳方法是什么?作文并不在我的脑海里,因为一个人没有“有”学生。我不是必须寻找解决方案,但可能只是一个搜索的术语或短语。由于我不确定该怎样称呼我正在尝试做什么,所以我没有太多运气。谢谢!

1 个答案:

答案 0 :(得分: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
?>

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