如何在同一控制器中将变量从一个函数传递到另一个函数

时间:2017-08-01 12:00:22

标签: codeigniter

我想将一个变量从一个函数传递给另一个函数,两者都在同一个控制器中,我使用Codeigniter,我的控制器代码是

public function passes() {
    $this->question();
    $this->load->view('passes', $data);
}

public function question() {
    if ($this->input->post('slug')) {
        $slug = $_POST['slug'];
        $slug = $this->Welcome_model->selectid($slug);
        $passcat_id = $slug[0]->id;
        log_message('error', 'collected id is ' . $passcat_id);
        $data['question'] = $this->Welcome_model->selectquestion($passcat_id);
    }
}

这是我的代码我想在视图页面中打印数据$ data ['question']。

谢谢。

4 个答案:

答案 0 :(得分:3)

您可以将代码更改为以下解决方案。

    public function passes() {
        $data = $this->question();
        $this->load->view('passes', $data);
    }

    public function question() {
        $data = array();
        if ($this->input->post('slug')) {
            $slug = $this->input->post('slug');
            $slug = $this->Welcome_model->selectid($slug);
            $passcat_id = $slug[0]->id;
            log_message('error', 'collected id is ' . $passcat_id);
            $data['question'] = $this->Welcome_model->selectquestion($passcat_id);
        }
        return $data;
    }

我希望这会对你有所帮助。谢谢!

答案 1 :(得分:1)

public function passes(){
    $data = $this->question();
    $this->load->view('passes',$data);
}

public function question()
{
if($this->input->post('slug')) {
        $slug = $this->input->post('slug');
        $slug = $this->Welcome_model->selectid($slug);
        $passcat_id = $slug[0]['id'];
        log_message('error', 'collected id is ' . $passcat_id);
        $data['question']= $this->Welcome_model->selectquestion($passcat_id);
         return $data;
}
}

我希望这会对你有所帮助。谢谢!

答案 2 :(得分:0)

请试试这个:

public function question($input)
{
     if(!emtpy($input) {
        $slug = $input;
        $slug = $this->Welcome_model->selectid($slug);
        $passcat_id = $slug[0]->id;
        log_message('error', 'collected id is ' . $passcat_id);
        $data['question']= $this->Welcome_model->selectquestion($passcat_id);
        return $data['question'];
     }

}
public function passes(){
     $this->question($_POST['input']);
     $this->load->view('passes',$data);
}

答案 3 :(得分:0)

您可以将flashdataredirect组合使用此

public function passes()
{
    // 3.) Get your question
    $question = $this->session->flashdata('item');
    // 4.) Pass to view
    $this->load->view('passes', ['question' => $question]);
}

public function question()
{
    if ($this->input->post('slug')) {
        $slug = $_POST['slug'];
        $slug = $this->Welcome_model->selectid($slug);
        $passcat_id = $slug[0]->id;
        log_message('error', 'collected id is ' . $passcat_id);
        $question = $this->Welcome_model->selectquestion($passcat_id);

        // 1.) Store your data in flash data
        $this->session->set_flashdata('question', $question);
        // 2.) Redirect to your passes function
        redirect('/yourcontroller/passes');
    }
}