duanjianhe1388
duanjianhe1388
采纳率100%
2014-05-29 10:07

OOP PHP的问题

已采纳

I am trying to build an admin part for my survey and I am using MVC pattern. I have in my database two tables:

Survey:      Answers: 
IdSurvey     Id
Question     Answer
Status       Counter
             IdSurvey
             Priority

In have two Classes: Survey and Answer. Class Survey has two fields: public $allAnswers; and public $IdSurvey and constructor:

public function __construct ( $idsurvey) 
{
$this->IdSurvey = $idsurvey; 
$this->allAnswers=Answer::GetAnswer($idsurvey);
}

In my Controller I have a method:

public function getSurveyForm($id)
{
$this->registry->template->survey = Survey::GetSurveyById($id);
}

this method GetSurveyById is in class Survey and looks like this:

public static function GetSurveyById($id)
{

$db=self::getInstance();

$query = $db->prepare("SELECT Question, status FROM survey WHERE IdSurvey=:IdSurvey");
$query->execute(array(':IdSurvey'=>$id));

$result = $query -> fetchObject();

return $result;

}

I need now, to echo selected survey with it's answers in View. And it's easy for the question, it would be:

$survey->Question;

but, I don't know how to get the answers!

If I make a new object in Controller: $this->registry->template->survey1 = new Survey($id);, than I can access to allAnswers, in View like this: $survey1->allAnswers;. Is there some way to get the answers without building this new object, just with the object $survey? I am very new to OOP, so I don't know is this a stupid question, but any help would be appreciated! Thank you!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanmianhong4893 duanmianhong4893 7年前

    You can create new Survey object, fill it with data from DB and return it in function GetSurveyById(). This will be more logically than returning stdObject created with fetchObject().

    It will be something like this:

    public static function GetSurveyById($id)
    {
        $db=self::getInstance();
    
        $query = $db->prepare("SELECT Question, status FROM survey WHERE IdSurvey='{$id}'");
        $query->execute();
    
        $result = $query->fetchObject();
    
        $survey = new Survey($id);
        $survey->Question = $result->Question;
        $survey->status = $result->status;
    
        return $survey;
    }
    

    You'd better use an ORM that deals with relations for these things but this will work too.

    点赞 评论 复制链接分享

相关推荐