2011-11-06 136 views
-1

這是我歡迎控制器從核心控制器笨

class Welcome extends MY_Controller 
{ 
    function __construct() 
    { 
     parent::__construct(); 

     $this->load->library('tank_auth'); 
    } 

    function index() 
    { 
     if (!$this->tank_auth->is_logged_in()) { 
      redirect('/auth/login/'); 
     } else { 
      $this->load->view('welcome', $player); 
     } 
    } 
} 
MY_Controller

class MY_Controller extends CI_Controller 
{ 
    function __construct() 
    { 
     parent::__construct(); 

     $this->load->library('tank_auth'); 

     if ($this->tank_auth->is_logged_in()) { 

      $player = $this->tank_auth->get_userdata($this->tank_auth->get_user_id()); 

      if ($player === NULL) { 
       $this->tank_auth->logout(); 
      } 
     } 
    } 
} 

我得到:

A PHP Error was encountered 

Severity: Notice 

Message: Undefined variable: player 

Filename: controllers/welcome.php 

Line Number: 17 
Hi, 
A PHP Error was encountered 

Severity: Notice 

Message: Undefined variable: username 

Filename: views/welcome.php 

Line Number: 1 

我真的需要重新分配所有的數據?還有其他方法嗎?

回答

1

$player設置在MY_Controller類的__construct()中。 index()如何在Welcome函數中自動獲取它的值?

而是將$player定義爲MY_Controller類中的受保護屬性,以便擴展它的每個控制器類都可以使用值$player

class MY_Controller extends CI_Controller 
{ 
    protected $player; 

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

     $this->load->library('tank_auth'); 

     if ($this->tank_auth->is_logged_in()) { 
      $this->player = $this->tank_auth->get_userdata($this->tank_auth->get_user_id()); 

      if ($this->player === NULL) { 
       $this->tank_auth->logout(); 
      } 
     } 
    } 
} 

現在,您的Welcome類可以使用它的值。

class Welcome extends MY_Controller 
{ 
    function __construct() 
    { 
     parent::__construct(); 

     $this->load->library('tank_auth'); 
    } 

    function index() 
    { 
     if (!$this->tank_auth->is_logged_in()) { 
      redirect('/auth/login/'); 
     } else { 
      $this->load->view('welcome', $this->player); 
     } 
    } 
} 
+0

驗證對象應該知道玩家,而不是控制器。 – hakre

+0

在代碼中,$ player的值在MY_Controller的__construct()中設置,並在Welcome控制器的index()中使用。所以你需要在MY_Controller的public/protected屬性中設置$ player的值,以便Welcome可以訪問它。另一種解決方案是執行'$ player = $ this-> tank_auth-> get_userdata($ this-> tank_auth-> get_user_id());'在Welcome中。 – Vikk