将控制器中定义的变量传递给CodeIgniter下的模型
问题描述:
I defined a variable in a method inside controller e.g.
class test extends CI_Controller {
function tester() {
$variable = 'value'
}
}
Now I want to call this variable in my model. How is that possible?
Edit: I use CodeIgniter.
我在控制器内的方法中定义了一个变量,例如 p>
class test扩展CI_Controller {
function tester(){
$ variable ='value'
}
}
code> pre>
现在我想调用这个变量 在我的模型中。 怎么可能? p>
编辑:我使用CodeIgniter。 p>
div>
答
Model:
class your_model extends CI_Model {
var $variable;
function __construct() {
parent::__construct();
}
function set_variable($variable) {
$this->variable = $variable;
}
}
Controller:
class test extends CI_Controller {
function tester() {
$this->load->model('your_model');
$variable = 'value'
$this->your_model->set_variable($variable);
}
}
答
FYI - if you need a variable available for more then one method in a controller and/or in your model - you can set it in the 'constructor' of the class. Use $this-> before the variable name.
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
// Set var in construct
$this->variable123 = 'some value 123' ;
} // end construct
You can now call $this->variable123 from anywhere in the class and it will be available. If you load a model from this class, it will be available to any method in the model.