【问题标题】:How can I achieve this kind of relationship (inheritance, composition, something else)?我怎样才能实现这种关系(继承、组合、其他)?
【发布时间】:2011-02-04 00:10:37
【问题描述】:

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

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

【问题讨论】:

  • 你已经在 Student 中覆盖了isStudent(),对吧?
  • 我可以,是的。在 Student 类中, isStudent() 始终为真。如果我有一个基本 Person 类的实例,isStudent() 可能是也可能不是。

标签: php design-patterns inheritance class composition


【解决方案1】:
<?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
?>

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

【讨论】:

  • 感谢您的回复。但是,基本 Person 类中的 isStudentFunc() 并不总是返回 false。如果它返回 true,我希望能够做这样的事情: $myPerson1 = new Person(); if($myPerson1->isStudentFunc()) { $myPerson1->mymethod(); }
猜你喜欢
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 2021-01-20
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多