Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在codeigniter 2中传递变量_Codeigniter_Codeigniter 2 - Fatal编程技术网

如何在codeigniter 2中传递变量

如何在codeigniter 2中传递变量,codeigniter,codeigniter-2,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-&g

我有以下几点

<?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
  }
}

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

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
  }

如果它是类的一部分,则可以将其放入构造函数中

 class Hello extends CI_Controller {

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

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

} 

是的,这将起作用,提醒新手您需要自动加载会话并配置加密以存储在会话变量中。