如何使用codeigniter将isset值传递给多个视图

时间:2014-05-16 14:54:46

标签: php codeigniter

我有isset()值来计算原始计数,并在 admin_messages.php 页面中显示计数我想将相同的值传递给 view_home.php 我怎么能这样做?

这是查看

<li>
    <a href="#">
        <i class="icon-home"></i> Inbox 
        <strong><?php if(isset($count)){echo $count;}?></strong>
    </a>
</li>

这是我的控制器

function messages() {

    $data['records'] =  $this->mod_contactus->get_records();
    $data['count'] =$this->mod_contactus->message_count();

    $this->load->view('admin/admin_messages',$data);

}

1 个答案:

答案 0 :(得分:1)

控制器是你的朋友。试试这个 - 它使用魔术方法__construct()。显然编辑它以满足您的需求。

<?php

 class MyController extends CI_Controller {
   private $message_count = 0;

   // Code called here is executed when the class is initialised, don't forget to call parent::__construct(); to execute the Codeigniter init code too.

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

      $this->load->model('mod_contact');
      $this->message_count = $this->mod_contact->message_count();

   }

   public function messages() {
        $data['records'] =  $this->mod_contactus->get_records();
        $data['count'] = $this->message_count;

        $this->load->view('admin/admin_messages',$data);
   }

   public function another_function() {
        $data['records'] =  $this->mod_contactus->get_records();
        $data['count'] = $this->message_count; // same value

        $this->load->view('admin/another_function',$data);
   }

 }