CodeIgniter:控制器中的全局变量 [英] CodeIgniter: global variables in a controller

查看:18
本文介绍了CodeIgniter:控制器中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 CodeIgniter 的新手,当我继续学习时,我遇到了在程序编码中很容易解决的问题

I'm a very newbie on CodeIgniter, and while I go on I run into problems that, in the procedural coding, were easy to fix

当前的问题是:我有这个控制器

The current issue is: I have this controller

class Basic extends Controller {

    function index(){
        $data['title'] = 'Page Title';
        $data['robots'] = 'noindex,nofollow';
        $data['css'] = $this->config->item('css');
        $data['my_data'] = 'Some chunk of text';
        $this->load->view('basic_view', $data);
    }

    function form(){
        $data['title'] = 'Page Title';
        $data['robots'] = 'noindex,nofollow';
        $data['css'] = $this->config->item('css');
        $data['my_other_data'] = 'Another chunk of text';
        $this->load->view('form_view', $data);
    }
}

如您所见,一些数组项一遍又一遍地重复:

As you can see, some array items repeat over and over:

$data['title'] = 'Page Title';
$data['robots'] = 'noindex,nofollow';
$data['css'] = $this->config->item('css');

有没有办法让它们在控制器中全局化",这样我就不必为每个函数输入它们?类似的东西(但这给了我错误):

Isn't there a way to make them "global" in the controller, so that I have not to type them for each function? Something like (but this gives me error):

class Basic extends Controller {

    // "global" items in the $data array
    $data['title'] = 'Page Title';
    $data['robots'] = 'noindex,nofollow';
    $data['css'] = $this->config->item('css');

    function index(){
        $data['my_data'] = 'Some chunk of text';
        $this->load->view('basic_view', $data);
    }

    function form(){
        $data['my_other_data'] = 'Another chunk of text';
        $this->load->view('form_view', $data);
    }

}

提前致谢!

推荐答案

你可以做的是制作类变量",可以从控制器中的任何方法访问.在构造函数中,您设置这些值.

What you can do is make "class variables" that can be accessed from any method in the controller. In the constructor, you set these values.

class Basic extends Controller {
    // "global" items
    var $data;

    function __construct(){
        parent::__construct(); // needed when adding a constructor to a controller
        $this->data = array(
            'title' => 'Page Title',
            'robots' => 'noindex,nofollow',
            'css' => $this->config->item('css')
        );
        // $this->data can be accessed from anywhere in the controller.
    }    

    function index(){
        $data = $this->data;
        $data['my_data'] = 'Some chunk of text';
        $this->load->view('basic_view', $data);
    }

    function form(){
        $data = $this->data;
        $data['my_other_data'] = 'Another chunk of text';
        $this->load->view('form_view', $data);
    }

}

这篇关于CodeIgniter:控制器中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆