如何在codeigniter 2中传递变量

时间:2012-11-30 02:13:29

标签: codeigniter codeigniter-2

我有以下

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Hello extends CI_Controller {
  var $name = 'test';
  function index() {
    $this->name = 'Andy';
    $data['name'] = $this->name;
    $this->load->view('you_view', $data);  // THIS WORKS
  }

  function you() {
    $data['name'] = $this->name;
    $this->load->view('you_view', $data);  // BUT THIS DOESN'T WORK
  }
}

我的问题是如何将$this->name = 'Andy';传递给you() ??

2 个答案:

答案 0 :(得分:0)

由于它是在控制器的不同方法中设置的,这相当于代码中的另一个请求,因此您需要将其存储在会话变量中,以使其在页面请求中保持不变。

function index() {
    $this->name = 'Andy';
    $data['name'] = $this->name;
    $this->session->set_userdata('name', $this->name);
    $this->load->view('you_view', $data);  // THIS WORKS
  }

  function you() {
    $data['name'] = $this->session->userdata('name');
    $this->load->view('you_view', $data);  // BUT THIS DOESN'T WORK
  }

答案 1 :(得分:0)

如果它是一个类的一部分,你可以把它放在构造函数

 class Hello extends CI_Controller {

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

    // will be available to any method in the class
    $this->name = 'andy';

}