在同一控制器中的函数之间传递变量


pass variable between functions in same controller

class AppointmentsController extends AppController {
public function view($id = null) {
    if (!$this->Appointment->exists($id)) {
        throw new NotFoundException(__('Invalid appointment'));
    }
    $options = array('conditions' => array('Appointment.' . $this->Appointment->primaryKey => $id));
    $this->set('appointment', $this->Appointment->find('first', $options));
    $kk = $this->Appointment->find('first',  array('fields' => 'status', 'conditions' => array('Appointment.id' => $id)));
    $ss = reset($kk);
    $stats = reset($ss);
}
}

我已经通过从DB获取值来设置$stats,我想在同一控制器的另一个函数中使用

那么我想这样使用

class AppointmentsController extends AppController {
function confirm(){
$stats = 'New';
}
}
看到

它是同一个类,您是否尝试过使用 $this->stats 而不是局部变量?

您可以在第一个函数中调用另一个函数,例如

$this->confirm($status); // calling confirm function
function confirm($status)
{
 //use status as you want
}

或者您可以将状态设置为全局变量,然后您可以在任何函数中访问。

我认为

,您必须在模型中创建函数,该函数将通过id返回字段的值。

<?php
// model/AppModel.php
public function getFieldById($field='id', $id){
  return $this->field($field, array('id' => $id));
}

// in controller function you can access this like.
$status = $this->Appointment->getFieldById('status', $id); // $id will be appointment id.
?>