英文:
Generating dynamic quiz questions without using eval
问题
我想创建一个测验,从一组问题中随机抽取20个问题,例如80个问题中抽取。但我希望这些问题能够包含一些脚本元素,比如随机数字、生成的图像和代码片段。
显而易见的答案是将这些代码放入数据库中并使用 eval 函数:
$query_from_db = '<div><?php
//要运行的 PHP 代码
function dosomething() {
//做一些事情
}
?></div>';
php echo eval($query_from_db);
然而,我知道这是不正确的,我不想这样做,请不要告诉我不要使用 eval。我需要了解如何以不同的方式处理这个问题。我应该将我的代码放入不同的包含文件中并调用它们吗?我应该使用模板引擎吗?我应该将它们放入单独的 PHP 文件中并调用它们吗?
这样做是为了使问题能够由动态代码组成,包括随机数字、随机图形、随机文本,在每个参与者参与时都会实时生成。
英文:
I want to create a quiz, where I can pull 20 random questions from a set of say, 80. I want the questions however to be able to have some scripted elements, such as random numbers, generated images and code snippets.
The obvious answer would be to put this code in the database and use eval
$query_from_db = '<div>
<?php
//php to run
function dosomething() {
//bleh
}
?>
</div>
';
php echo eval($query_from_db);
However I know this is wrong and I don't want to do this, please don't tell me not to use eval. What I need is to be able to understand how I can approach this from a different way. Should I put my code in different includes and call it, should I use template engine, should I put it in separate PHP files and call them?
This is so the questions can be made up of dynamic code for random numbers, random graphs, random text, generated on the fly for each person who takes it.
答案1
得分: 4
我的建议是不要使用“eval”方法,而是为每个问题添加一些参数,在它们发送到浏览器之前可以替换掉。
您可以查看“sprintf”函数,以格式化的方式将参数替换到字符串中。
您的参数的格式(我会添加到不同的字段/字段中)取决于您希望通过测验以及其中的问题来实现什么目标。
英文:
My suggestion would be to NOT use an eval
approach and instead add some parameters for each question which can be substituted out before they are sent to the browser.
You may want to have a look at the sprintf
function for substituting into strings in a formatted manner.
The format of your parameters (which I'd add into a different field/fields) depends on what you're hoping to achieve with your quiz and the questions in it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论