OOP基础知识 - 生成随机q& a

时间:2013-07-11 13:50:02

标签: php arrays function oop object

我正在尝试创建一个为表单验证目的创建随机安全问题的函数。我正在努力,因为我似乎无法访问变量的最终值。除了php.net之外的任何帮助都会受到赞赏,我一直在那里,但我不是100%了解如何创建我的第一个对象。

class question {

public $sq = '';
public $answer = '';

function generate_question() {

    $questions = array( array( question => "What color is the sky?",
                                answer => "blue"),
                        array(question => "What month is after April?",
                                answer => "May"),
                        array(question => "What animal is usually chasen by a cat?",
                                answer => "mouse"),
                        array(question => "What color is banana?",
                                answer => "yellow"),
                        array(question => "What is a 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;

1 个答案:

答案 0 :(得分:1)

方法只能返回一个值,不会达到其他返回值。

更改此代码

$question = array_rand($questions);

return $sq = $questions[$question]['question'];
return $answer = $questions[$question]['answer'];

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

它会起作用。

要访问返回数组,请使用

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

好的做法是给我们访问类变量的方法。这些变量应声明为私有,访问它们的方法应该是公共的。您还应该将带有问题答案的数组声明为私有对象变量。每次调用方法时都不需要声明它。

我已经将你的课程重新设计为更好(不是最佳)的解决方案。

class Question
{

    private $questions;

    public function __construct()
    {
      $this->questions = array( array( question => "What color is the sky?",
                            answer => "blue"),
                    array(question => "What month is after April?",
                            answer => "May"),
                    array(question => "What animal is usually chasen by a cat?",
                            answer => "mouse"),
                    array(question => "What color is banana?",
                            answer => "yellow"),
                    array(question => "What is a 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'];

已编辑&工作