0

我想在构造函数中设置一些数据,但是如果我像这样设置它:$data['something'] = 'val';,它不起作用。是否可以在构造函数中设置一些数据,这些数据将在同一控制器的所有其他函数中可用,然后在视图中?

4

3 回答 3

3

把它放在构造函数上

$data['something'] = 'val';
$this->load->vars($data);

注意不要在其他函数中使用 $data['var']=value 如果您已经在构造函数方法中声明它,因为它会覆盖构造函数变量

于 2013-07-26T13:54:09.467 回答
1

试试这个:

如果您将其发送到视图,则所有控制器都可以访问您设置的“stuff”数据:

<?php

Class Something Extends CI_Controller {

    var $data = array(); //the data variable that will be available in all methods.

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

        $this->data['stuff'] = 'do stuff'; //the data that you set on constructor
    }


    function index(){
        $this->data['controller_stuff'] = 'controller stuff';

        $this->load->view('yourview',$this->data); //both the 'stuff' and 'controller_stuff' will be sent to the view like this.
    }

}
于 2013-07-26T13:56:54.343 回答
0

试试这个:

class globalExample extends CI_Controller
{
    public $variable = "wow";
    public function one()
    {
        echo $this->variable; // wow
    }
    public function two()
    {
        echo $this->variable; // wow
    }

}
于 2013-07-26T13:55:36.923 回答