首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >OOP基础知识-生成随机问答

OOP基础知识-生成随机问答
EN

Stack Overflow用户
提问于 2013-07-11 21:50:02
回答 1查看 135关注 0票数 0

我正在尝试创建一个函数,用于创建一个用于表单验证目的的随机安全问题。不过,我正在苦苦挣扎,因为我似乎无法访问变量的最终值。除了php.net以外的任何帮助都将不胜感激,我一直在那里,但我不是100%理解如何创建我的第一个对象。

代码语言:javascript
运行
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-11 21:52:12

方法只能返回一个值,否则将无法返回另一个值。

更改此代码

代码语言:javascript
运行
复制
$question = array_rand($questions);

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

代码语言:javascript
运行
复制
$question = array_rand($questions);
return $questions[$question];

它会起作用的。

要访问返回数组,请使用

代码语言:javascript
运行
复制
echo $sqo->answer['question'];
echo $sqo->answer['answer'];

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

我已经将您的类重新设计为更好(不是最好)的解决方案。

代码语言:javascript
运行
复制
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'];

编辑和工作

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17595193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档