0

アプリケーション用のクラスの基盤をセットアップしたいと思います。そのうちの 2 つは個人と学生です。人は学生かもしれないし、そうでないかもしれませんし、学生は常に人です。学生が「人」であるという事実により、継承を試すようになりましたが、人のインスタンスを返す 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 に答える