2011-06-16 70 views
7

有誰知道如何訪問公共控制器變量,它已被其他功能更新的價值? 代碼示例 控制器訪問公共變量的值笨控制器

class MyController extends CI_Controller { 

public $variable = array(); 

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

function index(){ 
    $this->variable['name'] = "Sam"; 
    $this->variable['age'] = 19; 
} 

function another_function(){ 
    print_r($this->variable); 
} 

}

當我打電話another_function()我得到一個空數組..可能是什麼問題呢? 任何幫助將apreciated ..當你到那個特定頁面

+0

愚蠢的問題,你有沒有所謂的指數()? – 2011-06-16 12:46:39

+1

這應該工作,它看起來像e'index()'沒有被調用。 – Dunhamzzz 2011-06-16 12:46:44

回答

9

你必須利用構造函數,而不是指數()。

class MyController extends CI_Controller { 

    public $variable = array(); 

    function __construct() { 
     parent::__construct(); 
     $this->variable['name'] = "Sam"; 
     $this->variable['age'] = 19; 
    } 

    function index(){ 

    } 

    function another_function(){ 
     print_r($this->variable); 
    } 
    } 

如果你想打電話index(),然後調用another_function(),請嘗試使用CI session類。

class MyController extends CI_Controller { 

public $variable = array(); 

function __construct() { 
    parent::__construct(); 
    $this->load->library('session'); 
    if ($this->session->userdata('variable')) { 
     $this->variable = $this->session->userdata('variable'); 
    } 
} 

function index(){ 

    $this->variable['name'] = "Sam"; 
    $this->variable['age'] = 19; 
    $this->session->set_userdata('variable', $this->variable); 
} 

function another_function(){ 
    print_r($this->variable); 
} 
     } 
+0

老,但我的金子。 Thaks tpae – 2017-09-26 11:11:14

2

index()功能只叫,即index.php/mycontroller/index所以要index.php/mycontroller/another_function不會調用index()功能。如果您需要用戶去索引頁第一(以獲得他們的詳細信息),那麼首先定向他們那裏和細節保存到數據庫或會話變量。如果你事先知道的值(即它總是將是「山姆」和「19」,然後把該代碼在構造函數,它被調用每次你從控制器訪問一個頁面的時間。