duanjianhe1388 2014-05-29 10:07 采纳率: 100%
浏览 52
已采纳

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 2014-05-29 10:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程