2012-06-09 40 views
0

我想在php類中聲明一個可用於其所有函數的變量。我使用codeigniter框架&必須在每個函數中傳遞base_url等數據。另外我需要將所有這些數據都放在一個變量中。例如$data['base_url']=base_url(),$data['title']="My_Site_title"等&然後只發送一個變量$ data(這在codeigniter中是很常見的事情)。php類中的變量可用於其所有功能

this問題,我修改了代碼:

class Search extends CI_Controller { 

function Search() { 
    parent::__construct(); 
    $this->load->model('student_model'); 

    $this->load->helper('form'); 
    $this->load->helper('url'); 
    $this->output->enable_profiler(TRUE); 

    $this->data['base_url']=base_url(); //gives an error here 
} 

function index() { 
    $this->load->view('search_view', $this->data); 
} 
} 

但它仍然給人以明顯的地方出現錯誤,說Undefined variable: dataFatal error: Cannot access empty property in ..\search.php on line 16

+0

不能使用$數據沒有實例 – Sam

回答

1

在這裏你去:

class Search extends CI_Controller { 

protected $data = array(); 

function Search() { 
    parent::__construct(); 
    $this->load->model('student_model'); 

    $this->load->helper('form'); 
    $this->load->helper('url'); 
    $this->output->enable_profiler(TRUE); 

    $this->data['base_url']=base_url(); 
} 

function index() { 
    $this->load->view('search_view', $this->data); 
} 
} 

更多關於在PHP類屬性:http://php.net/manual/en/language.oop5.properties.php

+0

非常感謝:) – gopi1410