0

我有以下

<?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';to you()??

4

2 回答 2

0

如果它的值是类的一部分,您可以将它放在构造函数中

 class Hello extends CI_Controller {

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

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

} 
于 2012-12-01T01:29:56.150 回答
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
  }
于 2012-11-30T02:24:45.203 回答