我正在用PHP代码点火器做一个测试。我正在尝试使用一个函数来增加每个正确答案的分数。目前我没有向视图传递任何东西,我在控制器中有这个:
if ($res == true)
{
$scoreIncrement = 1;
$scoreResult = $this->Starmodel->increment($scoreIncrement);
var_dump($scoreResult);
如果quess是正确的,我将值1传递给函数increment,并转储结果以查看结果。这是我在模型中的函数:
var $score; //variable to hold the total score.
function increment($increment){
$this->score = $this->score + $increment;
return $this->score;
}
每次运行应用程序时,我总是从var_dump中得到1。变量var$score在模型中持久?此外,我正在单击"下一步",这意味着我正在加载函数以显示一条新消息,也许这是在重置结果。如何在模型中设置一个变量来保持当前分数?感谢
使用会话。
您似乎没有意识到这样一个事实,即每个答案都会调用一个新的PHP进程。
PHP一遍又一遍地从表单或请求中通过href。。
每次请求都会重新初始化您的内部数据,从而得到结果。
查找会话以实现请求之间的持久性。
http://php.net/manual/en/features.sessions.php
您可以使用SESSIONS或COOKIES来实现所谓的"数据持久性"
http://php.net/manual/en/features.cookies.php
Setting new cookie
=============================
<?php
setcookie("name","value",time()+$int);
/*name is your cookie's name
value is cookie's value
$int is time of cookie expires*/
?>
Getting Cookie
=============================
<?php
echo $_COOKIE["your cookie name"];
?>
您还可以将当前分数放在隐藏的表单字段中
// in your view form
echo form_hidden('currentscore',$this->score);
然后在表单提交后提取值
// pass to your method to increase the score
$currentscore = $this->input->post( 'currentscore') ;
$score = $currentscore + 1 ;
意见:使用$this->确实很强大,但它可能会变得笨拙。如果需要将值传递给模型中的方法,请考虑只显式传递。
function incrementScore($increment,$score){
$scoretotal = $increment + $score;
return $scoretotal;
}