0

我有几个$data几乎在控制器的所有函数中都被调用。有没有办法在__construct函数中创建这个$data并将它们与被调用函数中的$data结合起来?例子:

function __construct() {
        parent::__construct();

        $this->load->model('ad_model', 'mgl');
        $this->load->model('global_info_model', 'gi');
        $this->load->model('user_model', 'um');        
        $this->load->library('global_functions');
        $this->css = "<link rel=\"stylesheet\" href=\" " . CSS . "mali_oglasi.css\">";
        $this->gi_cat = $this->gi->gi_get_category();
        $this->gi_loc = $this->gi->gi_get_location();        
        $this->gi_type = $this->gi->gi_get_type();       
        }

    function index() {     
        $count = $this->db->count_all('ad');        
        $data['pagination_links'] = $this->global_functions->global_pagination('mali_oglasi', $count, 2);

        $data['title'] = "Mali Oglasi | 010";
        $data['oglasi'] =  $this->mgl->mgl_get_all_home(10);
        $data['loc'] = $this->gi_loc;
        $data['cat'] = $this->gi_cat;
        $data['stylesheet'] = $this->css;
        $data['main_content'] = 'mali_oglasi';

    $this->load->view('template',$data);
    }

如果我想把$data['loc']$data['cat']$data['stylesheet']放在__construct我将不得不在$ this->load->view( '模板',$数据);

有没有办法将这两者结合起来?

4

2 回答 2

3

将私有成员添加到您的控制器并根据需要在构造函数中设置它:

private $data;

function __construct() {
    ...
    $this->data = array(...);
    ...
}

然后,您可以在同一控制器类中的所有控制器操作中访问此私有成员。

您可以使用数组联合运算符 ( +)合并两个数组

$data = $this->data + $data;

另见:Properties Docs

于 2012-09-30T10:44:54.310 回答
2

当然,你可以这样做,

class ControllerName extends CI_Controller {

    private $_data = array();

    function __construct()
    {
        $this->_data['loc'] = this->gi_loc;
        $this->_data['cat'] = this->gi_cat;
        $this->_data['stylesheet'] = this->css;
    }

    function index()
    {
        // Your data

        // Merge them before the $this->load->view();
        $data = array_merge($this->_data, $data);
    }
}
于 2012-09-30T10:45:43.997 回答