开发者

Problem with static variable in cakephp

I have a controller like this:

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'));
    }
  }
}       

After adding a student to an array the count is incrementing and I am writing to session开发者_如何学Python variable student count. I have added 3 students and i am doing echo $this->Session->read('student_count'); in view but getting 0 every time.

I asked this question just few minutes ago, but the solution was not clear to me. Please tell me what piece of code to be added in the controller to get the number of students added in the view.


You're never incrementing the value of $count, and the static designation does not cause the variable to retain its value in subsequent requests, as PHP has no application state. You can fudge application state by reading and writing to your session var, in the same way you are doing with your Student collection.

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 */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜