0

我有这个控制器

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

     function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('text');

    }

    public function index()
    {
        $this->home();
    }

    public function home()
    {
            $data['title']="Somesite";
        $this->load->view("view_home", $data);

    }

        public function blog()
    {
            $data['title']="Somesite";
        $this->load->view("view_blog", $data);

    }
        public function answers()
    {
            $data['title']="Somesite";
        $this->load->view("view_answers", $data);

    }
    }

正如你所见,$data['title']对于所有函数都是一样的,如何使它更简单,在开始时包含而不是在每个函数中都写,再次重复,然后转移到视图。有没有办法将其转移到功能?

4

3 回答 3

3

在构造函数之前添加:

public $data = array();

然后在构造函数中写:

$this->data['title']="Somesite";

最后在加载视图之前添加:

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

现在你到处都有相同的$title 。

于 2013-06-14T14:38:26.287 回答
2

这是将一个变量传输到所有视图的简单解决方案和优雅:)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

    //Class-wide variable to store stats line
    protected $title;

    function __construct()
    {
        parent::__construct();
        $data->title = "Some site";
        $this->load->vars($data);
    }
于 2013-06-14T15:02:09.243 回答
0

我在每个项目中都使用这种方法。

控制器

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {

 //Global variable
 public $outputData = array();  
 public $loggedInUser;


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

 public function index()    {
    $this->load->helper('url');

    $this->load->view('users/users');
 }


 public function register() {

     parent::__construct();

     $this->load->helper('url');
     $this->load->model('users_model');

     //get country names
     $countryList = $this->users_model->getCountries();
     $this->outputData['countryList'] = $countryList;   


     $this->outputData['pageTitle'] = "User Registration";


    $this->load->view('users/register',$this->outputData);
 } 

}

查看文件

<?php if(isset($pageTitle)) echo $pageTitle; ?>

<?php
    if(isset($countryList)){
       print_r($countryList);
    }
?>
于 2014-07-05T14:12:46.137 回答