php - OOP Basics - generating a random q&a -


i'm trying create function creates random security question form validation purposes. i'm struggling though, can't seem access final values of variables. other php.net appreciated, i've been there don't 100% understand how create first object.

class question {  public $sq = ''; public $answer = '';  function generate_question() {      $questions = array( array( question => "what color sky?",                                 answer => "blue"),                         array(question => "what month after april?",                                 answer => "may"),                         array(question => "what animal chasen cat?",                                 answer => "mouse"),                         array(question => "what color banana?",                                 answer => "yellow"),                         array(question => "what next day after monday?",                                 answer => "tuesday"),                         );      $question = array_rand($questions);      return $sq = $questions[$question]['question'];     return $answer = $questions[$question]['answer'];         }  } $sqo = new question();  echo $sqo->sq . $sqo->answer; 

method can return 1 value other return won't reached.

change code

$question = array_rand($questions);  return $sq = $questions[$question]['question']; return $answer = $questions[$question]['answer']; 

to

$question = array_rand($questions); return $questions[$question]; 

and work.

to access return array use

echo $sqo->answer['question']; echo $sqo->answer['answer']; 

the practice methods access class variables. these variables should declared private , method accessing them should public. should declare array questions answers private object variable. there no need declare every time when method invoked.

i've redesigned class better(not best) solution.

class question {      private $questions;      public function __construct()     {       $this->questions = array( array( question => "what color sky?",                             answer => "blue"),                     array(question => "what month after april?",                             answer => "may"),                     array(question => "what animal chasen cat?",                             answer => "mouse"),                     array(question => "what color banana?",                             answer => "yellow"),                     array(question => "what next day after monday?",                             answer => "tuesday")                     );     }      public function generate_question()     {         return $this->questions[rand(0, count($this->questions)-1)];     }  }  $sqo = new question();  $question = $sqo->generate_question(); echo $question['question']; echo $question['answer']; 

edited & working


Comments