cakephp中的静态变量问题

时间:2011-03-09 13:14:11

标签: php cakephp

我有一个像这样的控制器:

class StudentsController extends AppController {
  var $name = "Student";


  function addstudent() {
    //$id=$_REQUEST['id'];
    //$this->Session->write('id', $id);
    static $count = 0;
    if(!empty($this->data)) {
      $students = $this->Session->read('Student');
      if(!$students) {
        $students = array();
      }
      $students[] = $this->data['Student']; /* data */
      $this->Session->write('Student', $students);
      $this->Session->write('student_count',$count);

      //$this->Session->write('Student',$this->data['Student']);
      //$this->Session->setFlash($this->Session->check('Student'));
      //print_r($this->data);
      //print_r($this -> Session -> read());
      //$this->Session->setFlash('student has been saved.');

      $this->redirect(array('controller'=>'students','action' => 'addstudent'));
    }
  }
}       

将学生添加到数组后,计数正在递增,我正在写入会话变量学生计数。我添加了3名学生,我正在查看echo $this->Session->read('student_count');,但每次都会获得0

几分钟前我问过这个问题,但解决方案对我来说并不清楚。请告诉我在控制器中添加哪些代码以获取视图中添加的学生数量。

1 个答案:

答案 0 :(得分:0)

您永远不会递增$count的值,static指定不会导致变量在后续请求中保留其值,因为PHP没有应用程序状态。您可以通过阅读写入会话var来捏造应用程序状态,就像使用Student集合一样。

function addstudent()
{
    if (!$count = $this->Session->read('student_count')) {
        $count = 0;
    }

    /* other operations in your action */

    $count++;
    $this->Session->write('student_count', $count);

    /* remaining bits of your action */
}