Codeigniter 2.1 - 组合来自__construct和被调用函数的$ data

时间:2012-09-30 10:40:51

标签: php codeigniter codeigniter-2

我有几个 $ 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-&gt; loading-&gt;视图中调用 $ this-&gt;数据('template',$ data );

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

2 个答案:

答案 0 :(得分:3)

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

private $data;

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

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

您可以使用array union operator (+)Docs合并两个数组:

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

请参阅:PropertiesDocs

答案 1 :(得分: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);
    }
}