从代码点火器函数我正在加载一个带有参数的库,它执行一堆事情并初始化库实例。 将此实例传递给另一个函数的正确方法是什么?
编辑:
public function init()
{
//...
$dataArr = array('directory' => $myDir, 'run' => TRUE);
$this->load->library('lib_mylib', $dataArr);
// here I want to pass the lib_mylib instance to final();
// lib my lib has variables that gets set when loaded, I don't want to reloaded it again in the next function because it performs some operations that should only happen once. How can I get a handle of that initiliazed library inside final?
}
public function final($inputLibMyLib)
{
}
答案 0 :(得分:2)
假设此代码在Controller中,只需在Controller的构造函数中加载库...
class Example extends CI_Controller {
// load your Controller wide library here
public function __construct()
{
parent::__construct();
$dataArr = array('directory' => $myDir, 'run' => TRUE);
$this->load->library('lib_mylib', $dataArr);
}
public funciton init()
{
$this->lib_mylib->function(); // is available
}
public funciton final()
{
$this->lib_mylib->function(); // is also available
}
}
每次请求函数时都会调用此构造函数。
的澄清强> 的
在构造函数中执行此操作是最佳选择,因为它可以保证在以下任何函数之前加载它。
...然而
如果您按顺序调用函数,则加载的库将保持...
例如
class Example extends CI_Controller {
// load your Controller wide library here
public function __construct()
{
parent::__construct()
}
public funciton init()
{
$dataArr = array('directory' => $myDir, 'run' => TRUE);
$this->load->library('lib_mylib', $dataArr);
$this->lib_mylib->function(); // is available
// call next function
$this->final();
}
public funciton final()
{
// is also available if final() is called from within init()
$this->lib_mylib->function();
}
}
答案 1 :(得分:-1)
只需确保将库实例by reference传递给您的函数,它应该可以正常工作。