2011-03-09 82 views
0

静态变量我有一个这样的控制器:问题与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

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

+0

我觉得你的静态$计数= 0应该是你添加学生 – 2011-03-09 13:21:18

+0

@Louskan否则它会被重新初始化每次方法的“走出去”:不,'static'的工作方式是,它只是初始化一次,它的价值保留每一个后续的电话。 – BoltClock 2011-03-09 13:31:32

+1

也许是复制/粘贴错误,但是您永远不会在代码段中增加$ count变量。 – dhofstet 2011-03-09 13:54:07

回答

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