2013-09-26 38 views
0

我有这样的笨控制器:为什么不能传递控制器功能之间的可变的笨

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

'hello()'没有'$ this-> idioma'设置为任何东西。 –

回答

3

如果您希望自动设置类属性,您可以在构造函数中执行,而不是在index()中执行。如果直接调用index(),则不会在其他方法之前运行。在你的情况,我假设你打电话问候通过URL作为测试/你好

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); 
    } 
} 
+0

谢谢!我认为index()作为构造函数工作... – harrison4

相关问题