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

查看:342
本文介绍了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);
    }

}

Thnaks提前!

Thnaks in advance!

推荐答案

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

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天全站免登陆