Kal*_*tel 0 php oop codeigniter
我试图在控制器的索引函数中初始化数据,以便初始化的数据可以用在控制器的后续功能中.但问题是,当我尝试从其他功能访问数据时,数据未显示.所有这些只是为了遵循一种面向对象的模式.
这是我的代码.
class Dashboard extends CI_Controller
{
private $account_data; /*Declaration*/
private $profile_data;
function __construct() {
// code...
}
function index() /*Here I am initializing data*/
{
$this->load->model('db_model');
$this->account_data = $this->db_model->get_row();
$this->profile_data = $this->db_model->get_row();
$this->load->view('user/dashboard');
}
function function account_details()
{
print_r($this->account_data); // This displays nothing
}
/*other function...*/
}
Run Code Online (Sandbox Code Playgroud)
想法是获取一次数据并将其用于其他功能,如果再次更新数据则调用函数来初始化它.
但它没有成功.请帮我.还建议我是否遵循正确的方法.谢谢你的时间.
index方法不是初始化程序,它的默认页面/ sub_method,如果你在url中调用"*account_details*"作为index.php/dashboard/account_details索引不会被调用.
尝试将代码放在构造函数上,
class Dashboard extends CI_Controller
{
private $account_data; /*Declaration*/
private $profile_data;
function __construct() { /*Here I am initializing data*/
parent::CI_Controller(); // Thank you Sven
$this->load->model('db_model');
$this->account_data = $this->db_model->get_row();
$this->profile_data = $this->db_model->get_row();
}
function index()
{
$this->load->view('user/dashboard');
}
function function account_details()
{
print_r($this->account_data); // This displays nothing
}
/*other function...*/
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您不需要此控制器的所有方法,请不要使用__construct()上的模型或其他计算.
创建一个私有方法,如" model_initializer()"将此代码放在此范围内,并在您的其他方法中调用它,就像$this->model_initialize();您需要一样.
谢谢你们Sesama Sesame,
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |