如何在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';
}
是的,这将起作用,提醒新手您需要自动加载会话并配置加密以存储在会话变量中。