2010-04-03 91 views
0

我想建立一個應用程序類的基礎,其中兩個是人和學生。一個人可能是也可能不是學生,學生永遠是一個人。事實上,一個學生「是一個」的人導致我嘗試繼承,但我不知道如何使它在我有一個返回人的實例的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

回答

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

我會選擇一種方式並堅持下去。只是去了各種想法和技巧。

+0

感謝您的回覆。基礎Person類中的isStudentFunc()不會總是返回false。如果它返回true,我希望能夠做到這樣的事情: $ myPerson1 = new Person(); if($ myPerson1-> isStudentFunc()){$ myPerson1-> mymethod(); } – Tim 2010-04-03 17:02:28