0

我正在尝试创建一个为表单验证目的创建随机安全问题的函数。不过我很挣扎,因为我似乎无法访问变量的最终值。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;
4

1 回答 1

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'];

编辑和工作

于 2013-07-11T13:52:12.193 回答