我在codeigniter控制器中有这个:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller {
public $idioma;
public function index() {
parent::__construct();
// get the browser language.
$this->idioma = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
$data["idioma"] = $this->idioma;
$this->load->view('inicio', $data);
}
public function hello(){
$data["idioma"] = $this->idioma;
$this->load->hello('inicio', $data);
}
}
Inicio观点:
<a href="test/hello">INICIO <?php echo $idioma ?></a>
你好观点:
Hello <?php echo $idioma ?>
inicio视图效果很好,但是当加载hello视图时,没有显示任何内容。 知道为什么这不起作用吗?
答案 0 :(得分:3)
如果您希望自动设置类属性,则可以在构造函数中进行,而不是在index()中进行。如果直接调用index(),则它们不会在其他方法之前运行。在你的情况下,我假设你通过url调用hello作为test / hello
class Test extends CI_Controller {
public $idioma;
public function __construct(){
parent::__construct();
// get the browser language.
$this->idioma = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
}
public function index() {
$data["idioma"] = $this->idioma;
$this->load->view('inicio', $data);
}
public function hello(){
$data["idioma"] = $this->idioma;
$this->load->hello('inicio', $data);
}
}