如何在CodeIgniter的两个方法中访问一个变量


How to make a variable accessible in 2 methods in CodeIgniter?

我有2个方法在我的控制器,一个负责生成注册页面,另一个负责处理注册表单提交。

<?php
class Signup_c extends CI_Controller {
    function __construct() {
        parent::__construct();
    }
    function index() {
        $data['title'] = 'Sign Up';
        $data['months'] = array(
            '1' => 'January',
            '2' => 'February',
            '3' => 'March',
            '4' => 'April',
            '5' => 'May',
            '6' => 'June',
            '7' => 'July',
            '8' => 'August',
            '9' => 'September',
            '10' => 'October',
            '11' => 'November',
            '12' => 'December'
        );      
        $this->load->view('signup_v', $data);
    }
    function submit() {
            // validation rules here...
        // validate
        if ($this->form_validation->run() === FALSE) {
            $this->load->view('www/signup_v');
        }
        else {
                    // add info to database here...
            $this->load->view('www/signup_success_v');
        }
    }
}

现在的问题是,如果存在验证错误,那么用户将返回到注册页面并显示验证错误。但是没有显示标题或日期,因为这些变量是在index()方法而不是submit()方法中定义的。

什么是最好的解决方案,我不想重复我的自我和复制这两个变量声明在注册方法太。是否有一种方法可以使它在两个方法的视图中工作?

为什么不分配类变量?在构造:

$title = 'Whatever';
$months = array('january', 'february');

然后在方法中使用$this->title和$this->months

访问它们

另外,为什么不直接返回到你的索引方法,让它在做其他事情之前做后处理呢?index方法的开头是这样的:

if(!empty($_POST))
{
    // do some kind of validation here
    // or call a private method in this class and set your class vars accordingly
}

您可以将validation_errors();保存在一些变量中,如sessions flashdata,如:

$this->session->set_flashdata('errors', validation_errors());

,然后在表单上方回显它们(例如)。我想这是最好的练习。

顺便说一句。你必须为这个

加载sessions模块

如何将数据存储在静态数组中,如果它保持不变(即静态)?

<?php
class Signup_c extends CI_Controller {
    // private because no one else needs to access this
    private static $data = array('title' => 'Sign Up', 'months' => array(...));
    function __construct() {
        parent::__construct();
    }
    function index() {
        $this->load->view('signup_v', Signup_c::$data);
    }
    function submit() {
        // validation rules here...
        // validate
        if ($this->form_validation->run() === FALSE) {
            $this->load->view('www/signup_v', Signup_c::$data);
        }
        else {
            // add info to database here...
            $this->load->view('www/signup_success_v'); // maybe add it here, too?
        }
    }
}

或者,将用户重定向回索引可能是有意义的。不幸的是,我对CI了解不多,所以我不是提供建议的合适人选。

我想到的另一件事是:为什么需要在控制器中使用月份数组?我相信有更好的办法。可以考虑将其放在模板中。毕竟,月份不变,还是我忽略了什么?