【问题标题】:Codeigniter 2.1 - Combining $data from the __construct and called functionCodeigniter 2.1 - 结合来自 __construct 和被调用函数的 $data
【发布时间】:2012-09-30 10:40:51
【问题描述】:

我有几个 $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('template',$data);

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

【问题讨论】:

    标签: php codeigniter codeigniter-2


    【解决方案1】:

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

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

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

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

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

    另请参阅:PropertiesDocs

    【讨论】:

    • 这是基本的 PHP,你可以将它用于你的所有类,无论是控制器还是其他东西。学习基础知识很有用;)
    • 嗯,我是一个自学成才的程序员,所以我可能跳过了一些基本课程:D
    • 这与是否自学无关。这只是要看的地方:)
    【解决方案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);
        }
    }
    

    【讨论】:

    • 这是有效的。谢谢你的帮助:)(很抱歉没有得到支持,但 hakra 是第一个)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多